#75: map vs flatMap vs compactMap

These three methods are easy to confuse, but their jobs are different.

[1, 2, 3].map { $0 * 2 }
[[1, 2], [3]].flatMap { $0 }
["1", "x", "3"].compactMap(Int.init)

map transforms each element. flatMap flattens nested sequences. compactMap transforms and drops nil results.

If you keep those three ideas in mind, choosing the right one becomes much easier.


I'm also on Twitter and GitHub.

Subscribe via RSS.