Member-only story

How to Use Key Path Expressions as Functions in Swift

An awesome new feature in Swift 5.2

Sagun Raj Lage
Better Programming

--

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:

--

--

No responses yet