Skip to content

Instantly share code, notes, and snippets.

@blixt
Last active December 16, 2015 21:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blixt/3ebed2b87fb32b1ca65a to your computer and use it in GitHub Desktop.
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
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