Swift version: 5.6
The compactMap()
method lets us transform the elements of an array just like map()
does, except once the transformation completes an extra step happens: all optionals get unwrapped, and any nil values get discarded.
This is useful whenever you have an array of things you need to convert, but the conversion process might fail.
For example, consider this array of strings:
let numbers = ["1", "2", "Fish"]
Two of those hold a number, but one does not. We can use compactMap()
to convert those to integers, because creating an Int
from a String
is a failable initializer – it returns an Int?
because you might have passed an invalid number.
compactMap()
will read those optional integers, unwrap all the optionals for us, then discard any items that returned nil
, all in one line of code:
let integers = numbers.compactMap { Int($0) }
When that code runs, integers
will hold an array of Int
rather than an array of Int?
.
SAVE 50% To celebrate Black Friday, 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.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Available from iOS – learn more in my book Pro Swift
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Link copied to your pasteboard.