Better Programming

Advice for programmers.

Follow publication

Member-only story

How to Use Key Path Expressions as Functions in Swift

Sagun Raj Lage
Better Programming
Published in
2 min readApr 26, 2020
Photo by Meritt Thomas on Unsplash

Consider this piece of code:

Here, we’ve created a struct named Car with five properties: model, brand, releaseDate, price, designerName and isExpensive.

Let’s create some instances of this struct and store them in an array, cars:

Note: The names of the cars and their properties do not resemble the cars in real world.

If we want to retrieve the models of all the cars in the cars array, up to Swift 5.1, the syntax would be as follows:

let carModels = cars.map({ car in
return car.model
})

Or, if that developer is a bit lazy (like me!) or prefers to write short code, the code would be:

let carModels = cars.map { $0.model }

But wait, Swift 5.2 has something for you! The Swift Evolution Proposal SE-0249, authored by Stephen Celis and Greg Titus, reviewed by Ben Cohen and implemented in Swift 5.2, has introduced a handy approach to use key paths in some special cases. The Evolution Proposal describes this as being able to use “\Root.value wherever functions of (Root) -> Value are allowed”. What this means is that if previously you sent a Car into a method and got back its model, you can now use Car.model instead.

To put it simply, starting from Swift 5.2, you can use key path to select that particular iteration and access its properties. Hence, we can fetch the models of all cars in cars array by writing:

let carModels = cars.map(\.model)

It’s as simple as that! Key paths make it easy and quick.

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Sagun Raj Lage
Sagun Raj Lage

Written by Sagun Raj Lage

Author of Getting Started with WidgetKit (2021) | iOS Engineer | Full Stack Engineer

No responses yet

Write a response