/ ios

flatMap(_:) vs flatMap(_:) vs compactMap(_:)

With Swift 4.1 and when working with arrays, Apple deprecated flatMap(_:) to compactMap(_:). But there may be some confusion about flatMap(_:)...

The deprecated one

The flatMap(_:) method that allowed to return an array of the non-nil results of a transformation of each element of an array was deprecated and renamed compactMap(_:).

let array = [[1, 2], nil, [3, 4, 5], [6, 7]] // -> [[Int]?]

let flatMapped = array.flatMap { $0 }
// returns [[1, 2], [3, 4, 5], [6, 7]]
let compactMapped = array.compactMap { $0 }
// also returns [[1, 2], [3, 4, 5], [6, 7]]

But wait, just like Master Yoda said...

There is another

One flatMap(_:) is still there. And it does not do the same thing at all.

let array = [[1, 2], [3, 4, 5], [6, 7]] // -> [[Int]]

let flatMapped = array.flatMap { $0 }
// returns [1, 2, 3, 4, 5, 6, 7]

As you can see, this method just flattened our array into another one.

It's actually an equivalent to calling map(_:) and joined() on an array.

Conclusion

Yes, you've heard right. Swift 4.2 deprecated flatMap(_:) and you should now use compactMap(_:). But there was another one.

Now we clearly have to distinct method name for two distinct behavior.

So just be careful, don't Find and Replace all "flatMap" occurrences in your whole project! You may have some bad surprises.

flatMap(_:) vs flatMap(_:) vs compactMap(_:)
Share this

Subscribe to David Yang