Last active
December 16, 2015 21:26
-
-
Save blixt/3ebed2b87fb32b1ca65a to your computer and use it in GitHub Desktop.
Using flatMap to convert a list of mixed nils and values into a list of non-optional values
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
let numbers = [ | |
"one", | |
"2", | |
"0x3", | |
"42", | |
] | |
// This will run the function on all values and only keep the ones that are not nil: | |
let parsedNumbers = numbers.flatMap { Int($0, radix: 10) } | |
// [2, 42] | |
// flatMap also works directly on optionals so you don't have to check for nil before: | |
let doubled = Int("123", radix: 10).flatMap { $0 * 2 } | |
// 246 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment