Prior to the Swift 4.1 I used flatMap
to remove nil
values from collections. Now this method is deprecated and I need to replace it with compactMap
. Sometimes I used flatMap
with lazy collections to optimise my code, like that:
let optionalIntegers : [Int?] = [1, 2, nil, 3, 4, nil, nil, 5]
optionalIntegers.lazy.flatMap { $0 }.forEach { print("Item \($0 * 10)") }
Will it has the same effect if I will use compactMap
instead of flatMap
? In documentation for the method lazy
I found references to map
and filter
only.
Yes, absolutely the same. They just decided to remove the ambiguity of flatMap
functions and renamed one of them to compactMap
not to confuse developers.
Here is the proposal: Introduce Sequence.compactMap(_:)
We propose to deprecate the controversial version of a Sequence.flatMap method and provide the same functionality under a different, and potentially more descriptive, name.