Skip to content

Instantly share code, notes, and snippets.

@harlanhaskins
Created July 6, 2015 19:00
Show Gist options
  • Save harlanhaskins/78c7b1edaf110c237c42 to your computer and use it in GitHub Desktop.
Save harlanhaskins/78c7b1edaf110c237c42 to your computer and use it in GitHub Desktop.
mapMaybe.swift
// 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