In Swift, what decides whether a key-path expression is a KeyPath, WritableKeyPath or ReferenceWritableKeyPath, and why does a generic settings row care?
answer
- a class hierarchy of key paths
- let, get-only and hidden setters
- value root vs class reference
- inout root vs let reference
basics
~20 sThe path decides: any read-only step gives KeyPath, settable steps through values give WritableKeyPath, and a settable member behind a class reference gives ReferenceWritableKeyPath. A settings row that writes must demand WritableKeyPath, so read-only properties fail to compile.
solid answer
~40 sSwift's key-path types are a class hierarchy: `AnyKeyPath`, `PartialKeyPath<Root>`, `KeyPath<Root, Value>`, `WritableKeyPath` and `ReferenceWritableKeyPath`, each a subclass of the one before. The compiler picks the type from the path: a `let`, a get-only computed property, a setter you cannot see from here or an optional-chaining step make it a read-only `KeyPath`; settable `var`s and subscripts on value types make it a `WritableKeyPath`, which writes through a mutable (`var` or `inout`) root; a settable member reached through a class reference makes it a `ReferenceWritableKeyPath`, which writes even through a `let` root. A settings `ToggleRow` that stores `WritableKeyPath<Settings, Bool>` therefore rejects `\.isBeta` when `isBeta` is a `let`, at compile time, while a read-only `LabelRow` taking `KeyPath` accepts every path.
code
swift · 34 linesstruct Settings {
var darkMode = false
var fontSize = 14
let isBeta = true
var summary: String { "\(fontSize) pt" }
}
struct ToggleRow {
let title: String
let value: WritableKeyPath<Settings, Bool>
func flip(_ settings: inout Settings) {
settings[keyPath: value].toggle()
}
}
struct LabelRow<Value> {
let title: String
let value: KeyPath<Settings, Value>
func text(for settings: Settings) -> String {
"\(title): \(settings[keyPath: value])"
}
}
var settings = Settings()
let dark = ToggleRow(title: "Dark mode", value: \.darkMode)
dark.flip(&settings)
print(settings.darkMode) // true
print(LabelRow(title: "Size", value: \.summary).text(for: settings))
print(LabelRow(title: "Beta", value: \.isBeta).text(for: settings))
// ToggleRow(title: "Beta", value: \.isBeta)
// error: cannot convert value of type 'KeyPath<Settings, Bool>'
// to expected argument type 'WritableKeyPath<Settings, Bool>'go deeper
Recall the three common types: KeyPath reads, WritableKeyPath reads and writes on values, ReferenceWritableKeyPath reads and writes through a class reference.
Explain how let, get-only and inaccessible setters, optional chaining and class references decide the type, and why a mutable root is needed for WritableKeyPath.
Design generic rows or bindings that request the narrowest key-path type, and explain the PartialKeyPath erasure cost and the Sendable rule in Swift 6 mode.
Treat the key-path type as an API contract: asking for WritableKeyPath only where code writes keeps read-only models usable and moves mistakes to compile time.
## The key-path class hierarchy Swift's key paths are **classes** in the standard library, arranged so that each type can do everything its superclass can and a little more: | Type | Knows | Can do | |---|---|---| | `AnyKeyPath` | nothing statically; `rootType` and `valueType` are available as class properties at run time | read, with the result typed `Any?` | | `PartialKeyPath<Root>` | the root type | read from a `Root`, with the result typed `Any` | | `KeyPath<Root, Value>` | root and value types | read a `Value` | | `WritableKeyPath<Root, Value>` | root and value types | read, and write through a mutable root | | `ReferenceWritableKeyPath<Root, Value>` | root and value types | read, and write through any root, because the write lands in a class instance | Because they form a hierarchy, a `WritableKeyPath<Settings, Bool>` can be passed wherever a `KeyPath<Settings, Bool>` is expected, and a `KeyPath<Settings, Bool>` can be stored as a `PartialKeyPath<Settings>` in a heterogeneous list. `AnyKeyPath` conforms to `Hashable`, so every key path can also be a dictionary key, for example a `[PartialKeyPath<Settings>: String]` of row titles. ## How the compiler picks the type The type of an expression such as `\Settings.darkMode` is decided by its components, checked from the place where you write it: 1. **Read-only steps make it a `KeyPath`.** A `let` property, a computed property with only a getter, a property whose setter is not accessible here (such as `private(set) var` used outside its scope) and an optional-chaining step `?.` all produce `KeyPath`. 2. **Settable steps through values make it a `WritableKeyPath`.** A `var` stored property, a computed property with `get` and `set`, a subscript with a setter, a force-unwrap `!` and the identity path `\.self` keep it writable. 3. **A settable step reached through a class reference makes it a `ReferenceWritableKeyPath`.** For `final class Session { var token = "" }`, `\Session.token` is reference-writable; so is `\Holder.session.token` even when `session` is a `let` stored property, because the write modifies the object, not the `let`. A `WritableKeyPath` writes through a mutable root: `settings[keyPath: path] = true` needs `settings` to be a `var` or an `inout` parameter. A `ReferenceWritableKeyPath` writes through a `let` root as well, because the root only locates the object. ## Why a generic settings row cares A settings form wants one generic row type per kind of control instead of one hand-written view model per setting. The key-path type is the row's contract: - A `ToggleRow` stores `WritableKeyPath<Settings, Bool>` and flips the value with `settings[keyPath: value].toggle()` on an `inout Settings`. - A `LabelRow<Value>` only displays, so it stores `KeyPath<Settings, Value>` and accepts stored, computed and `let` properties alike. - Passing `\.isBeta`, a `let`, to `ToggleRow` fails at compile time with `cannot convert value of type 'KeyPath<Settings, Bool>' to expected argument type 'WritableKeyPath<Settings, Bool>'`. The mistake is caught where the row is created, not at run time when the user taps the toggle. Asking for the narrowest capability the row needs is the rule: a row that never writes should ask for `KeyPath`, so read-only properties remain usable. ```swift struct Settings { var darkMode = false } struct ToggleRow { let title: String let value: WritableKeyPath<Settings, Bool> func flip(_ settings: inout Settings) { settings[keyPath: value].toggle() } } ``` ## The same expression, different types Because the compiler checks access where the expression is written, one spelling can produce two types: - For `struct Counter { private(set) var value = 0 }`, `\Counter.value` is a `WritableKeyPath<Counter, Int>` inside `Counter` and its extensions in the same file, and a `KeyPath<Counter, Int>` at top level or in another file, where the setter is not visible. - For a class, `\Session.self` is a `WritableKeyPath<Session, Session>`, not a reference-writable one: the identity path replaces the reference stored in a variable rather than writing into the object. - An explicit annotation can widen the static type: `let p: KeyPath<Settings, Bool> = \.darkMode` stores a writable path as a read-only `KeyPath`, which is how a read-only API accepts writable paths. ## Type erasure and its cost Rows of different value types cannot share an array of `KeyPath<Settings, Bool>`. Storing them as `PartialKeyPath<Settings>` works, but reading through a `PartialKeyPath` returns `Any`, and writing is no longer possible without casting back with `as?` to the concrete writable type. A common design keeps the concrete key path inside each row value and erases the row instead, so the write path stays typed. ## What to remember - The hierarchy runs `AnyKeyPath`, `PartialKeyPath`, `KeyPath`, `WritableKeyPath`, `ReferenceWritableKeyPath`. - One read-only step makes the whole path read-only; a class reference along the way makes a settable path reference-writable. - Ask for the least capability an API needs, and let the compiler reject paths that cannot be written.
- In Swift 6 language mode, why does a Sendable ToggleRow struct storing WritableKeyPath<Settings, Bool> fail to compile?The key-path classes do not conform to `Sendable`, so a `Sendable` struct cannot store a plain `WritableKeyPath`; Swift 6 mode reports an error that the stored property has a non-Sendable type, and Swift 5 mode reports the same diagnostic as a warning. Declare the property as `WritableKeyPath<Settings, Bool> & Sendable`: since Swift 6.0 (SE-0418), Swift 6 mode infers `& Sendable` for a key-path literal like `\.darkMode` that captures no non-Sendable values.
- Why can you assign through a ReferenceWritableKeyPath on a let constant but not through a WritableKeyPath?A `WritableKeyPath` mutates the root value itself, so the root must be mutable: a `var` or an `inout` parameter. A `ReferenceWritableKeyPath` passes through a class reference, and the write modifies the object that reference points to; the `let` constant holding the reference is not changed, so the compiler allows it.
- Which key-path type does \Settings.self have, and what can you do with it?`\Settings.self` is the identity path, a `WritableKeyPath<Settings, Settings>`. Applied with `settings[keyPath: \.self] = Settings()` it replaces the whole value in one write, which is useful as a reset row in a generic form.
- Every key path to a var is a ReferenceWritableKeyPath.
- WritableKeyPath and KeyPath are unrelated types, so neither converts to the other.
- A key path through an optional chain is writable like any other.
- A WritableKeyPath can write through a let struct constant.
- Key paths are strings at run time, so a typo is only found when the row is used.
Assumes Swift 6.4 in either language mode; only the Sendable follow-up depends on the mode: key-path literals are inferred & Sendable in Swift 6 mode (SE-0418, Swift 6.0).