Skip to content

Instantly share code, notes, and snippets.

@ikesyo
Last active December 16, 2015 02:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ikesyo/8877f7c6d0cfb9ffab35 to your computer and use it in GitHub Desktop.
Save ikesyo/8877f7c6d0cfb9ffab35 to your computer and use it in GitHub Desktop.
Mapping with filtering nil
let values = [ "1", "foo", "3" ]
// Swift 1.2
extension Array {
func filterMap(@noescape transform: T -> U?) -> [U] {
var results = [U]()
for x in self {
if let mapped = transform(x) {
results.append(mapped)
}
}
return results
}
}
let numbers1: [Int?] = values.map { $0.toInt } // [ 1, nil, 3 ]
let numbers2: [Int] = values.filterMap { $0.toInt } // [ 1, 3 ]
// Swift 2
let numbers: [Int] = values.flatMap { Int($0) } // [ 1, 3 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment