Writable and Reference KeyPaths
Read and write through key paths.
Read-Only vs Writable Key Paths
A plain KeyPath can only read a value. To write through a key path you need a writable variant. Swift has two of them, one for value types and one for reference types.
This lesson covers WritableKeyPath for structs and ReferenceWritableKeyPath for classes, and how the [keyPath:] subscript becomes settable.
struct Person {
var name: String
var age: Int
}
let writable: WritableKeyPath<Person, Int> = \Person.age
print(type(of: writable))WritableKeyPath for Value Types
A WritableKeyPath targets a mutable stored property of a value type. To set through it, the instance itself must be a var, because mutating a struct property mutates the whole value.
Use the [keyPath:] subscript on the left side of an assignment to write.
struct Person {
var name: String
var age: Int
}
var alice = Person(name: "Alice", age: 30)
let agePath = \Person.age
alice[keyPath: agePath] = 31
print(alice.age)All lessons in this course
- KeyPath Basics
- Using KeyPaths in Collections
- Writable and Reference KeyPaths
- @dynamicMemberLookup