Skip to content

Instantly share code, notes, and snippets.

@jtbandes
Created August 12, 2015 03:45
Show Gist options
  • Save jtbandes/280974801d35a18bc1db to your computer and use it in GitHub Desktop.
Save jtbandes/280974801d35a18bc1db to your computer and use it in GitHub Desktop.
//import Foundation
//class P: NSObject {}
protocol P {}
class C: P {}
extension SequenceType
{
func mapAs<T>(type: T.Type) -> [T] {
return map { $0 as! T }
}
}
func doStuffWith(seq: AnySequence<AnyObject>) {
let a1 = Array(seq).map { $0 as! P } // works
let a2 = seq.map { $0 as! P } // works
// let a3 = Array(seq) as! [P] // works from AnyObject->P(a class), but doesn't work for Any->P or if P is a protocol
let a4 = seq.mapAs(P) // works! same as #2 really
}
let objs: [AnyObject] = [C(), C(), C()]
let things = AnySequence(objs) // AnySequence<AnyObject>
doStuffWith(things)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment