What the key path is in Swift

·

2 min read

The key path like \.example is almost inevitable when developing apps with Swift. Today, I will explain this important syntax.

Overview

In Swift, a key path is a way to refer to a property. It allows you to create a reference to a specific property without actually accessing directly. Key paths are represented by the KeyPath type in Swift.

Here is an example:

struct Person {
    var name: Strin
    var age: Int
}

// key path
let nameKeyPath: KeyPath = \Person.name // create a key path with explicit type 
let ageKeyPath: KeyPath = \Person.age // create a key path

As shown in the example above, you can define a key path variable with the backslash \ followed by the type name and property.

Once you define a key path, you can access properties using it like the following:

struct Person {
    var name: Strin
    var age: Int
}

// key path
let nameKeyPath: KeyPath = \Person.name // create a key path with explicit type 
let ageKeyPath: KeyPath = \Person.age // create a key path

let person1 = Person(name: "John", age: 30)
let person2 = Person(name: "Paul", 28)

// access the property using a key path
let person1Name = person1[keyPath: nameKeyPath] // "John"
let person2Age = person2[keyPath: ageKeyPath] //28

// update property values using a key path
person1[keyPath: ageKeyPath] = 31
person2[keyPath: nameKeyPath] = "George"

In this way, you can access properties using a key path and reuse it for another instance's properties.
Note
The keyPath in the expression person1[keyPath: nameKeyPath] is a parameter used as a subscript to access the value of a property using a key path.

Why and when is a key path useful?

You may think the key path is verbose and directly accessing a property will satisfy the issue. Yes, you can also access the values like the following:

struct Person {
    var name: Strin
    var age: Int
}

let person1 = Person(name: "John", age: 30)
print(person1.name) // John

However, using key paths offers several merits:

  • Dynamic Property Access: Key paths provide a way to refer to properties of a type dynamically, without hard-coding the property names. It allows you to access properties based on runtime values or user input.

  • Reusability: Instead of explicitly referring to specific properties, key paths are reusable that you do not need to call specific properties.

  • Convention: Key paths are commonly used in SwiftUI especially for data bindings. Therefore, you have to use key paths to utilize SwiftUI.