Last active
August 29, 2015 14:09
-
-
Save airspeedswift/392599e7eeeb74b481a7 to your computer and use it in GitHub Desktop.
Generic ExtensibleCollectionType algorithm plus a default Array version
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This algorithm returns a generic placeholder | |
// that can be any kind of extensible collection: | |
func mapSome | |
<S: SequenceType, C: ExtensibleCollectionType> | |
(source: S, transform: (S.Generator.Element)->C.Generator.Element?) -> C { | |
var result = C() | |
for x in source { | |
if let y = transform(x) { | |
result.append(y) | |
} | |
} | |
return result | |
} | |
// usage example: | |
let strings = ["1","2","3"] | |
let toInt = { (s: String) -> Int? in s.toInt() } | |
let a: Array = mapSome(strings, toInt) | |
let b: ContiguousArray = mapSome(strings, toInt) | |
// however, it's annoying to have to specify a type | |
// every time when you probably want an array. | |
// cue obscure Swift compiler error... | |
let c = mapSome(strings, toInt) | |
// If you write a second version that returns an array, | |
// you can call the more general version for implementation: | |
func mapSome<S: SequenceType,U>(source: S, transform: (S.Generator.Element)->U?)->[U] { | |
// just calls the more generalized version | |
// (works because here, the return type | |
// is now of a specific type, an Array) | |
return mapSome(source, transform) | |
} | |
// and now, if you don't specify, you get an array by default: | |
let d = mapSome(strings, toInt) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment