skip to content

In Swift, how do optional chaining, force unwrapping and subscripts inside a key path change its type, and what does appending(path:) return?

level: middleimportance: should knowfreq 25%

answer

  1. each component has its own rule
  2. ?. makes it read-only
  3. ! keeps it writable, can trap
  4. Hashable subscript arguments
  5. typed append vs erased append

basics

~20 s

Optional chaining makes a key path read-only with an Optional value; force unwrapping keeps it writable but traps on nil; subscripts need Hashable arguments. Typed appending(path:) returns a typed path; on PartialKeyPath or AnyKeyPath it returns an Optional.

solid answer

~40 s

A key path's path is a chain of components, and each one affects the result. `\Profile.address?.city` is a `KeyPath<Profile, String?>`: the value becomes optional and the path is read-only, so assigning through it fails with `cannot assign through subscript: key path is read-only`. `\Profile.address!.city` is a `WritableKeyPath<Profile, String>` that traps when `address` is `nil`. A subscript such as `\Profile.scores["swift"]` is allowed when every index is `Hashable`, and its arguments are evaluated once, when the key path is created. `appending(path:)` joins two key paths: the typed overloads return a non-optional path that is read-only when the appended part is read-only, reference-writable when a class reference is crossed and the rest is writable, and writable otherwise; on `PartialKeyPath` or `AnyKeyPath` it returns an optional that is `nil` when the root does not match.

code

swift · 23 lines
swift
struct Address { var city: String }
struct Profile {
    var address: Address?
    var scores: [String: Int]
}

var profile = Profile(address: Address(city: "Oslo"), scores: ["swift": 3])

let city = \Profile.address?.city      // KeyPath<Profile, String?>  (read-only)
let forced = \Profile.address!.city    // WritableKeyPath<Profile, String>
let score = \Profile.scores["swift"]   // WritableKeyPath<Profile, Int?>

print(profile[keyPath: city] as Any)   // Optional("Oslo")
profile[keyPath: forced] = "Bergen"    // traps if address is nil
profile[keyPath: score] = 5
// profile[keyPath: city] = "Paris"    // error: cannot assign through subscript: key path is read-only

let address = \Profile.address!
let joined = address.appending(path: \Address.city)   // WritableKeyPath<Profile, String>
print(profile[keyPath: joined], profile.scores)

let erased: PartialKeyPath<Profile> = \Profile.scores
print(erased.appending(path: \Address.city) as Any)   // nil: root type does not match

go deeper

for a junior

Recall that a key path can go through optionals and subscripts, and that a ?. step makes the value optional.

for a middle

Explain why ?. makes a path read-only, why ! keeps it writable at the cost of a trap, and why subscript arguments must be Hashable.

for a senior

Predict the type appending(path:) returns for each combination, including the reference-writable case and the optional result on erased key paths.

for a principal

Weigh force-unwrapped writable paths in generic code against modelling non-optional state, and know that key paths to methods are not available in shipping Swift.

## A key path is a chain of components A **key-path expression** such as `\Profile.address!.city` is a root type followed by a path, and the path is a list of **components**. The Swift book lists what a component can be: a property name, a subscript, an optional-chaining step `?` and a forced unwrap `!`, repeated in any order. Tuple elements are allowed too. Each component has its own rule, and the key path's final type, the read-only `KeyPath`, `WritableKeyPath` or `ReferenceWritableKeyPath`, is decided by the whole chain. ## Optional chaining and force unwrapping Given `struct Profile { var address: Address? }` and `struct Address { var city: String }`: | Expression | Type | Behaviour | |---|---|---| | `\Profile.address` | `WritableKeyPath<Profile, Address?>` | reads or replaces the optional | | `\Profile.address?.city` | `KeyPath<Profile, String?>` | reads `nil` when `address` is `nil`; cannot write | | `\Profile.address!.city` | `WritableKeyPath<Profile, String>` | reads and writes; traps when `address` is `nil` | Two consequences matter in code review: - **Optional chaining makes the path read-only.** Writing `profile[keyPath: \Profile.address?.city] = "Paris"` is a compile error, `cannot assign through subscript: key path is read-only`. To write, write the whole `address`, or use a `!` path only where `nil` is impossible. - **The value type becomes optional.** Code that receives `\.address?.city` as a `KeyPath<Profile, String?>` must handle `nil`, the same way an ordinary optional chain does. A force unwrap keeps the path writable, which makes it tempting in generic form code; the cost is a run-time trap, exactly as with `profile.address!.city`. The read-only rule is specific to key paths. The ordinary statement `profile.address?.city = "Paris"` compiles and simply does nothing when `address` is `nil`; the key path `\Profile.address?.city` has no such write. Code that needs "set the city if there is an address" writes that statement in a closure, or keeps a writable path to the optional `address` and assigns a whole new `Address`. ## Subscripts in a key path A path may include subscripts, such as `\[String].[1]` or `\Profile.scores["swift"]`, which is a `WritableKeyPath<Profile, Int?>` because `Dictionary`'s subscript has a setter and returns an optional. Two rules apply: 1. **Every subscript argument must be `Hashable`.** The key path stores the arguments, and key paths are themselves `Hashable`. An argument of a non-`Hashable` type fails with `subscript index of type 'NotHashable' in a key path must be Hashable`. 2. **Arguments are evaluated once.** A function call or variable inside the brackets is evaluated when the key-path expression is evaluated and captured by value; using the path later does not re-run it. ## Composing with appending(path:) `appending(path:)` joins a key path from `Root` to `Value` with one from `Value` to a new value, giving the same path as writing the dot-notation in one expression: `(\Profile.address!).appending(path: \Address.city)` equals `\Profile.address!.city`. The result type follows a table of overloads: - `KeyPath` + `KeyPath` gives `KeyPath`; `WritableKeyPath` + `WritableKeyPath` gives `WritableKeyPath`. - Appending a `KeyPath` to a `WritableKeyPath` or a `ReferenceWritableKeyPath` gives a `KeyPath`: one read-only step makes the whole path read-only. - Appending a `ReferenceWritableKeyPath` to a `KeyPath` or a `WritableKeyPath` gives a `ReferenceWritableKeyPath`, and a `ReferenceWritableKeyPath` + `WritableKeyPath` stays reference-writable: once a class reference is reached, the write goes into the object. - On a type-erased `PartialKeyPath<Root>` or `AnyKeyPath`, `appending(path:)` returns an **optional**, `nil` when the appended path's root does not match the first path's value type. With the typed overloads a mismatch is a compile error rather than `nil`, because both types are known. An appended path also compares equal to the written-out one: `\Profile.address!.city == (\Profile.address!).appending(path: \Address.city)` is `true`, so appended paths work as dictionary keys alongside literal ones. ## What a key path cannot contain The components are properties, subscripts, `?`, `!`, tuple elements and `self`. A **method** is not a component in Swift 6.4: `\User.greet()` fails with `key path cannot refer to instance method 'greet()'`. Key paths to methods and initializers were proposed in SE-0479, which was returned for revision, and the compiler keeps the work behind the experimental feature `KeyPathWithMethodMembers`, which the release compiler refuses to enable (`experimental feature 'KeyPathWithMethodMembers' cannot be enabled in production compiler`). A computed property that wraps the method is a common workaround. ## What to remember - `?.` gives a read-only path with an optional value; `!` keeps it writable and can trap. - Subscript arguments must be `Hashable` and are captured when the path is made. - Typed `appending(path:)` never returns `nil`; the erased versions do.

  • Why is \Holder.session.token reference-writable when session is a let stored property of a struct?
    Because `session` holds a class reference. The write through the key path modifies the object it points to, not the `let` property, so the compiler gives the path the type `ReferenceWritableKeyPath<Holder, String>`, the same result as appending `\Session.token` to `\Holder.session`.
  • When would you build key paths with appending(path:) instead of writing them out?
    When the parts are chosen separately, for example a form that holds a `WritableKeyPath<Settings, Address>` for a section and a list of `WritableKeyPath<Address, String>` for its fields. Appending each field to the section path gives typed paths from `Settings` without writing every combination by hand.

  • \Profile.address?.city can be used to write the city when address is set.
  • A force-unwrapped key path returns nil instead of trapping.
  • Any value can be used as a subscript argument in a key path.
  • appending(path:) always returns an optional key path.
  • Swift 6 lets you write \User.greet() as a key path to a method.

Assumes Swift 6.4: key paths to methods and initializers (SE-0479) are not shipped; the proposal was returned for revision and the feature stays experimental.