Last active
December 16, 2015 02:32
-
-
Save ikesyo/8877f7c6d0cfb9ffab35 to your computer and use it in GitHub Desktop.
Mapping with filtering nil
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
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