NEW: Get your ticket for Hacking with Swift Live 2019! >>

How to use compactMap() to transform an array

Swift version: 5.0

Paul Hudson    @twostraws   

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?.

UPGRADE YOUR SWIFT Hacking with Swift Live is a new iOS conference taking place in the UK this July, with all profits going to charity. Come and learn the major new APIs announced at WWDC19 with sessions and hands-on tutorials – click here to learn more!

Available from iOS – learn more in my book Pro Swift

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Click here to visit the Hacking with Swift store >>