Clicky

iOS Dev Nugget 200 Swift flatMap

.

Need to run a code review on your codebase? Hire me

Swift arrays have a flatMap function that is very handy. Suppose you have an array of Int and want to perform an operation for each element and return the results as a new array. This is the classic use of map:

let source1 = [1, 2, 3]
let l1 = source1.map {$0*2}
l1 //[2, 4, 6] of type [Int]

If the source array is of type [Int?], it becomes trickier:

let source2: [Int?] = [1, 2, nil, 3]
let l2 = source2.map {$0} //Can't easily do $0*2, we'll just use $0 for illustration
l2 //[{some 1}, {some 2}, nil, {some 3}] of type [Int?]

Notice that the result (l2) is now an [Int?]. Sometimes you want a [Int], discarding any nil values. This is where flatMap comes in:

let l1 = [1, 2, nil, 3].flatMap {$0}
l1 //[1, 2, 3]

The result is an [Int].

flatMap performs the operation and discards the value if it's nil. This is useful in this case:

let someSourceIdentifiers = ...
let objectsFound = someSourceIdentifiers.flatMap {lookupObject($0)}

There's another use of flatMap, which is to flatten arrays.

let l2 = [[1, 2], [3, 4, 5]].flatMap {$0}
l2 //[1, 2, 3, 4, 5]

In other words, it unpacks 1 level of array.

Notice how it doesn't unpack here:

let l3 = [1, [2, 3, 4], 5].flatMap {$0}
l3 //[1, [2, 3, 4], 5]


Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No

.

.

Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter

.

View archives of past issues