Sitemap
Better Programming

Advice for programmers.

How to Use Key Path Expressions as Functions in Swift

An awesome new feature in Swift 5.2

2 min readApr 26, 2020

--

Press enter or click to view image in full size
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:

--

--

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