Swift: map vs. flatMap For Dummies
tl;dr Summary
This is me, figuring out how map
and flatMap
work in Swift.
tl;dr Conclusions:
- Think of optionals as an array that can hold 1 or 0 items.
- Arrays and optionals are both containers that can have
map
orflatMap
applied -
map
unwraps a container, transforms value with supplied function and rewraps result. -
flatMap
unwraps a container, transforms value with supplied function and rewraps either a raw value, or the non-nil value of a contained result[confusing]
Complete Version With Complete Examples
Recently, I had an issue where I was using a tableView with multiple selection allowed, and I had a short array with names ([String]
), and I wanted a map
function that would return the index of that name in a larger array with all the possible names.
smallNameArray.map({ largeNameArray.indexOf($0)! })
However, .indexOf()
returns an optional value, and Swift won’t let map...