UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Transforming and unwrapping dictionary values with compactMapValues()

Available from Swift 5.0

Paul Hudson      @twostraws

SE-0218 adds a new compactMapValues() method to dictionaries, bringing together the compactMap() functionality from arrays (“transform my values, unwrap the results, then discard anything that’s nil”) with the mapValues() method from dictionaries (“leave my keys intact but transform my values”).

As an example, here’s a dictionary of people in a race, along with the times they took to finish in seconds. One person did not finish, marked as “DNF”:

let times = [
    "Hudson": "38",
    "Clarke": "42",
    "Robinson": "35",
    "Hartis": "DNF"
]

We can use compactMapValues() to create a new dictionary with names and times as an integer, with the one DNF person removed:

let finishers1 = times.compactMapValues { Int($0) }

Alternatively, you could just pass the Int initializer directly to compactMapValues(), like this:

let finishers2 = times.compactMapValues(Int.init)

You can also use compactMapValues() to unwrap optionals and discard nil values without performing any sort of transformation, like this:

let people = [
    "Paul": 38,
    "Sophie": 8,
    "Charlotte": 5,
    "William": nil
]

let knownAges = people.compactMapValues { $0 }

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Other changes in Swift 5.0…

Download all Swift 5.0 changes as a playground Link to Swift 5.0 changes

Browse changes in all Swift versions

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.