Swift Map vs CompactMap vs FlatMap

Understanding the differences

It can be confusing to remember the difference, so this is a cheatsheet for reference.

Swift .map()

map({}) transforms all elements in a list.

let list = ["about", "testing", "1", "100", "300"]
print(list)
// ["about", "testing", "1", "100", "300"]

let mappedList = list.map({ String($0.reversed()) })
print(mappedList)
// ["tuoba", "gnitset", "1", "001", "003"]

.compactMap()

compactMap() compacts the list, by removing the nil items. (filterMap was the original name for the function when it was proposed)

let list = ["about", nil, "testing", "1", nil, "100", "300", nil]
print(list)
// [Optional("about"), nil, Optional("testing"), Optional("1"), nil, Optional("100"), Optional("300"), nil]

let compactedList = list.compactMap({ $0 })
print(compactedList)
// ["about", "testing", "1", "100", "300"]

.flatMap()

flatMap() flattens a list of other lists by combining their contents.

let list = [ ["1", "2", "3"], ["a", "b", "c"], ["kyle", "harry", "tom"] ]
print(list)
// [["1", "2", "3"], ["a", "b", "c"], ["kyle", "harry", "tom"]]

let compactedList = list.flatMap({ $0 })
print(compactedList)
// ["1", "2", "3", "a", "b", "c", "kyle", "harry", "tom"]