Member-only story
How to Use Key Path Expressions as Functions in Swift
An awesome new feature in Swift 5.2

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.