Skip to content
DeveloperMemos

Exploring Swift's KeyPath Type

Swift, KeyPath, Type1 min read

Swift's KeyPath is a powerful feature that allows developers to reference and manipulate properties of objects in a type-safe manner. It is similar to a pointer to a member variable in C++, but with the added benefit of being type-safe.

To create a KeyPath, you start by specifying the type of object you want to reference, followed by the name of the property you want to reference. For example, if you have a struct called Person with a property called name, you can create a KeyPath to that property like this:

1struct Person {
2 var name: String
3}
4
5let nameKeyPath = \Person.name

Once you have a KeyPath, you can use it to get or set the value of the referenced property on an instance of the specified type. For example:

1let person = Person(name: "John")
2let name = person[keyPath: nameKeyPath] // "John"
3
4var newPerson = person
5newPerson[keyPath: nameKeyPath] = "Jane"
6print(newPerson.name) // "Jane"

You can also use KeyPaths with higher-order functions like map, filter and reduce. For example:

1let people = [
2 Person(name: "Alice"),
3 Person(name: "Bob"),
4 Person(name: "Charlie")
5]
6
7let names = people.map(\.name) // ["Alice", "Bob", "Charlie"]

In this example, we're using the map function to create a new array containing only the names of the people in the original array. We're doing this by passing a KeyPath that references the name property of each Person object to the map function.

KeyPaths can also be used with subscripting on collections. For example:

1let nestedArray = [[1, 2], [3, 4], [5, 6]]
2let firstElementKeyPath = \[[Int]].first?[Int].first
3
4let firstElement = nestedArray[keyPath: firstElementKeyPath] // 1

In this example, we're using a KeyPath to get the value of the first element of the first sub-array of a nested array.

In summary, Swift's KeyPath type is a powerful and flexible tool that allows you to reference and manipulate properties of objects in a type-safe manner. It can be used with a variety of higher-order functions and is particularly useful when working with collections of objects.