Use Key Paths in Swift
Written by Team Kodeco
Key paths in Swift are a way to refer to the properties of objects in a type-safe manner.
They allow you to dynamically extract and set the values of a property by providing a path to the property, rather than hard-coding the property name as a string. They are particularly useful when used in combination with functions like map
and compactMap
to extract values from an array of objects. KeyPaths can also be used with classes, structs, and enums that conform to the Codable
protocol to encode and decode custom data types.
The key path syntax in Swift consists of two parts:
- The
\
operator: This operator is used to create a key path expression. It is followed by the property or properties that you want to reference in the key path. For example:\Person.address.street
creates a key path that references the street property of theAddress
struct, which is a property of thePerson
struct. - The
[keyPath: xxx]
subscript syntax: This syntax is used to access the property’s value using the key path. ThekeyPath
argument specifies the key path to the property, andxxx
is a reference to the key path expression created using the\
operator. For example:person[keyPath: streetKeyPath]
accesses the value of the street property of thePerson
struct using the key path stored in thestreetKeyPath
constant.
Here’s a simple example of using key paths in Swift:
struct Person {
var name: String
var address: Address
}
struct Address {
var street: String
var city: String
}
let person = Person(name: "John Doe", address: Address(street: "1 Main St", city: "San Francisco"))
let streetKeyPath = \Person.address.street
let street = person[keyPath: streetKeyPath] // "1 Main St"
The \
in \Person.address.street
creates a key path to a specific property of an object. In this case, it creates a key path to the street
property of the Address
struct, which is a property of the Person
struct.
The value of the street
property can then be accessed using the key path with the person[keyPath: streetKeyPath]
syntax.