Skip to content
Tutorials Center
My learning

Topics

Lesson 105 of 146 ยท Standard Library and Foundation

Key Paths

Learn Swift key paths: KeyPath and WritableKeyPath, key paths as functions in map and sorted, appending paths, @dynamicMemberLookup and generic helpers.

Usually you read a property by writing it: person.name. The compiler turns that into a read the moment it compiles the line. A key path is different: it is a value that describes a property, without touching any instance. You write \Person.name and get back an object that means "the name of some Person", which you can store in a variable, pass to a function, compare with another key path, and later use to read or write the property of any person you like.

That sounds abstract, but you have probably already used the most common form: people.map(\.name). This lesson explains what the backslash syntax really creates, the family of key path types, how they act as functions, how to build reusable generic helpers with them, and how @dynamicMemberLookup uses them to forward properties. Key paths are checked at compile time, so a typo in a property name is an error, not a runtime surprise.

Writing and using a key path

The syntax is a backslash, a root type, and a path of members: \Person.name. To use it, you put it in the special [keyPath:] subscript that every type has:

Swift Reading and writing through key paths

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

print(nameKeyPath) shows \Person.name: the path prints as it was written. Reading ada[keyPath: nameKeyPath] gives Ada, and assigning through ageKeyPath changes age to 37 (the annotation shows we have a WritableKeyPath). The deeper paths read Ada (37), Optional("London"), code and 2. Anything you can write after a dot may appear in a path: stored and computed properties, optional chaining (?), force-unwrap (!), and subscripts with literal arguments (\.tags[1]).

When the compiler knows the root type from context you can leave it out: let ageKeyPath: WritableKeyPath<Person, Int> = \.age. That is the form you see in arguments such as people.map(\.name).

The key path types

Every key path is an instance of one of these classes. They form a family, from most specific to most general:

Type Meaning
KeyPath<Root, Value> read-only access to a Value inside a Root
WritableKeyPath<Root, Value> read and write, but only on a mutable Root variable
ReferenceWritableKeyPath<Root, Value> read and write on a class instance, even through a let
PartialKeyPath<Root> a path from Root to some value; the value type is erased
AnyKeyPath a path from some root to some value; both erased

Which one you get depends on the path. The output of the last four lines of the previous example is, in order, WritableKeyPath<Person, String>, KeyPath<Person, String> (a computed property with only a getter cannot be written), KeyPath<Person, Optional<String>> (a path that goes through ? is read-only, because writing through a possible nil is not meaningful) and KeyPath<Person, String> for \Person.address!.zip (the zip is a let).

Constants cannot be written

Making a key path to a let property is fine, and you can read through it. Writing is a compile-time error. This is the type system protecting you; it does not need a runtime check:

Swift Writing through a let property (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first assignment is fine. The second one fails because \.id is a plain KeyPath, and the compiler reports main.swift:8:9: error: cannot assign through subscript: 'settings' is immutable. The message blames the variable, which is a little misleading: the real reason is the read-only key path, because only a WritableKeyPath can be assigned through. Change let id to var id and the program prints Settings(id: 2, volume: 8).

Classes and reference types

For a class, a path to a var property is a ReferenceWritableKeyPath. Because an object is a reference, you can write through it even when the variable holding the object is a let:

Swift ReferenceWritableKeyPath on a class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

You see 5, then ReferenceWritableKeyPath<Counter, Int> and KeyPath<Counter, Int>, then 6. A struct would need var and an inout parameter for the same function. That is the value-versus-reference difference from Value vs reference types showing up in the type of the key path.

Key paths as functions

Since Swift 5.2 a key path expression can be used wherever a function from the root to the value is expected, so \Person.name can stand in for { $0.name }. This is the usage you will write most:

Swift Key paths where closures are expected

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The output is ["pen", "book", "lamp"], 13, ["book", "lamp"], pen, then [3, 1, 2], [1, 2, 3], [1, 2, 3], 10 and the first letters ["p", "b", "l"]. Note that this use is read-only and single-step: the key path becomes a function of one argument that returns a value. Anything with a different shape (two arguments, or an operator such as <) still needs a closure. For sorting, KeyPathComparator wraps a key path into a comparator.

Generic helpers built on key paths

The real power shows when you write a function that takes which property to use as an argument. A closure can do this too, but a key path is shorter at the call site, comparable, hashable and cannot do surprising work: it can only follow a path of properties.

Swift Functions that take a key path

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

You get 16 (the total quantity), ["book", "ink", "pen"], and then the groups 2 ["pen", "ink"] and 15 ["book"], and finally Item(name: "PEN", qty: 7, price: 2). Because the helpers are generic over T, they work for any struct or class, without a protocol and without knowing the type. The compiler checks that the property exists and has the type the function needs: total(stock, of: \.name) would not compile, since name is a String.

Partial and Any key paths

Sometimes you want to treat different properties of one type uniformly, in a list, ignoring their value types. That is what PartialKeyPath<Root> is for. Key paths are also Hashable, so they work as dictionary keys:

Swift PartialKeyPath, equality and dictionary keys

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The loop prints each label with its value (Desk, 4, 120), the cast gives stock is an Int: 5, the dictionary lookups print Unit price and unknown, and the last two lines print true and false. A PartialKeyPath forgets the value type, so reading through it produces Any, and you recover the real type with a cast. This is how table views and form builders describe columns and fields as data. Prefer the typed KeyPath<Root, Value> whenever you can; erasure costs you compile-time checking.

Building paths in pieces

Key paths can be joined with appending(path:), as long as the end type of the first is the start type of the second. There is one trap to know first. A key path literal stored in a let without a type annotation gets the static type KeyPath, even when the path is writable underneath, and everything you derive from it stays read-only:

Swift An unannotated key path is read-only (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler stops with main.swift:9:54: error: cannot convert value of type 'KeyPath<Car, Int>' to specified type 'WritableKeyPath<Car, Int>'. (Without the annotation on carPower, the failure would move to the assignment: cannot assign through subscript: 'carPower' is a read-only key path.) The fix is to say what you mean when you store the paths, as the next example does:

Swift Appending key paths

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

It prints 200, 250, WritableKeyPath<Car, Int> and true: the appended path is equal to the one you would write in a single expression. Appending is handy when a component knows only one part of a path (an engine panel knows \Engine.horsepower) and the caller supplies the way to reach the engine.

@dynamicMemberLookup

A type marked @dynamicMemberLookup can answer property accesses that it does not declare. It implements a subscript labelled dynamicMember. If that subscript's parameter is a key path, the compiler checks every use at compile time, and you can build wrappers that forward to another type's properties:

Swift Forwarding properties with dynamicMemberLookup

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

user.name and user.age never appear in Logged; the compiler rewrites them to the key path subscripts and prints Zoe 17 false. The assignment goes through the writable overload, and after it isAdult is true. Because the subscript takes a key path, user.nme is a compile error with the usual "has no member" message. The second form, with a String parameter, accepts any identifier: settings.timeout compiles and returns nil at run time (the output line is localhost 8080 -). That is more flexible, but you lose the safety. SwiftUI's @Binding, Observable wrappers and the Swift Testing framework use the key path form heavily.

Key paths work in Swift 6 with strict concurrency: key path literals without captured values are Sendable and can be shared between tasks. You may notice the type any KeyPath<String, Int> & Sendable in some compiler messages; that is why.

When to use key paths

  • Passing which property to a generic helper (sorted(by: \.date)).
  • Short map, filter and compactMap calls over a property.
  • Describing columns, fields or bindings as data (PartialKeyPath).
  • Forwarding properties with @dynamicMemberLookup.

Prefer a closure when you need to compute something ({ $0.price * $0.qty }), call a method, or combine several properties. Key paths follow properties only, not method calls. Be careful with stored key paths in a long-living object: a KeyPath to a class property is fine, but it does not capture any instance, so it cannot leak one (a closure capturing self can).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does \Person.name produce?

    A key path is a first-class description of a property. Nothing is read until you apply it, for example with person[keyPath: path].
  2. 2. Which key path type lets you assign to a property of a class instance held in a let constant?

    Because a class instance is a reference, writing through ReferenceWritableKeyPath does not need the variable to be mutable. A WritableKeyPath needs a mutable root.
  3. 3. What does people.map(\.name) do?

    Since Swift 5.2 a key path expression can be used where a function from the root to the value is expected, so .name is the same as { $0.name }.
  4. 4. Why is \Person.address?.city a read-only KeyPath?

    A path that passes through optional chaining may stop at nil, so Swift gives it the read-only KeyPath type. Using ! instead of ? can give a writable path.
  5. 5. What is the advantage of @dynamicMemberLookup with a key path parameter over one with a String parameter?

    With a key path parameter, a typo like user.nme is a compile error and each property keeps its real type. A String parameter accepts any name and resolves it at run time.

Summary

  • A key path (\Type.property) describes a property; apply it with instance[keyPath: path].
  • The types are KeyPath, WritableKeyPath, ReferenceWritableKeyPath, PartialKeyPath and AnyKeyPath; the compiler picks the most specific one that is valid.
  • Paths may go through optionals, array subscripts and computed properties; optional chaining and let properties make a path read-only.
  • A key path can be used as a function (map(\.name)), but only for reading a property.
  • Generic helpers that take a KeyPath<T, V> are short, type-safe and reusable; key paths are Hashable, so they can be dictionary keys.
  • appending(path:) joins paths; @dynamicMemberLookup with a key path forwards properties safely.

Next: Memory Layout