The flatMap()
method was useful for a variety of things in Swift 4.0, but one was particularly useful: the ability to transform each object in a collection, then remove any items that were nil.
Swift Evolution proposal SE-0187 suggested changing this, and as of Swift 4.1 this flatMap()
variant has been renamed to compactMap()
to make its meaning clearer.
For example:
let array = ["1", "2", "Fish"]
let numbers = array.compactMap { Int($0) }
That will create an Int
array containing the numbers 1 and 2, because "Fish" will fail conversion to Int
, return nil, and be ignored.
SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.
Download all Swift 4.1 changes as a playground Link to Swift 4.1 changes
Link copied to your pasteboard.