Created
July 6, 2015 19:00
-
-
Save harlanhaskins/78c7b1edaf110c237c42 to your computer and use it in GitHub Desktop.
mapMaybe.swift
This file contains 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
// Transform a list of values into a list of transformed values where the transformation might fail and produce an optional. | |
func mapMaybe<C : CollectionType, T>(array: C, transform: (C.Generator.Element -> T?)) -> [T] { | |
var result = [T]() | |
for element in array { | |
if let transformed = transform(element) { | |
result.append(transformed) | |
} | |
} | |
return result | |
} | |
mapMaybe(["1", "hello", "2"], String.toInt) | |
// > [1, 2] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment