KeyPath Basics
Reference properties as first-class values.
What Is a Key Path?
A key path is a value that describes a path to a property without actually accessing it. Think of it as a stored, reusable reference to which property you want, separate from which instance you read it from.
You write a key path with a backslash, the type name, a dot, and the property name. Swift gives this expression a KeyPath value that you can pass around like any other value.
struct Person {
let name: String
let age: Int
}
let nameKeyPath = \Person.name
print(type(of: nameKeyPath))Reading a Value
To read a property through a key path, use the [keyPath:] subscript on an instance. You pass the key path inside the brackets and Swift returns the value at that path.
This is the runtime counterpart to writing the property name directly, but now the property is chosen by data rather than hard-coded.
struct Person {
let name: String
let age: Int
}
let alice = Person(name: "Alice", age: 30)
let path = \Person.name
print(alice[keyPath: path])