Swift Higher Order Function: compactMap vs flatMap, Do you know the difference?

KD Knowledge Diet
2 min readApr 29, 2022

--

you might understand map, filter, reduce. But there are more useful functions to use! In particular, knowing the compact map can save you from writing all kinds of cumbersome code. But it’s sad to see people using only compactMap or only flatMap. Most people don’t even know the difference. The top 1% of developers are strong in detail. Let’s get to know the difference between flatMap and compactMap this time.

Similarity

let array1 = [1, nil, 3, nil, 5, 6, 7]
let flatMapTest1 = array1.flatMap{ $0 }
let compactMapTest1 = array1.compactMap { $0 }

print("flatMapTest1 :", flatMapTest1)
print("compactMapTest1 :", compactMapTest1)

// result
flatMapTest1 : [1, 3, 5, 6, 7]
compactMapTest1 : [1, 3, 5, 6, 7]

Those two functions look like doing the same thing by unwrapping optional values. But you will see this message. ‘flatMap’ is deprecated: Please use compactMap(:) for the case where closure returns an optional value
Use ‘compactMap(:)’ instead.

let array2: [[Int?]] = [[1, 2, 3], [nil, 5], [6, nil], [nil, nil]]
let flatMapTest2 = array2.flatMap { $0 }
let compactMapTest2 = array2.compactMap { $0 }

print("flatMapTest2 :",flatMapTest2)
print("compactMapTest2 :",compactMapTest2)

// result
// flatMapTest2 : [Optional(1), Optional(2), Optional(3), nil, Optional(5), Optional(6), nil, nil, nil]
// compactMapTest2 : [[Optional(1), Optional(2), Optional(3)], [nil, Optional(5)],

flatMap do not remove nils, they only remove nils when they are one-dimensional arrays.
flatMap flattens a 2D array into a 1D array, whereas compactMap doesn’t make it into a 1D array.

In other words, flatMap can be used to flatten a 2D array into 1D!

The output of flatMapTest2 above is optional, but since it is a one-dimensional array, you can get the desired value by chaining it to compactMap, right?

Conclusion

From Swift 4.1, when you want to remove nil from a one-dimensional array and do unwrapping optional value, use compactMap.
FlatMap is used to flatten a 2D array into a 1D array.

--

--

KD Knowledge Diet

Software Engineer, Mobile Developer living in Seoul. I hate people using difficult words. Why not using simple words? Keep It Simple Stupid!