In Swift, how does contacts.map(\.name) work, and why does passing a stored KeyPath variable to map fail?
answer
- a literal standing in for a closure
- (Root) -> Value from \Root.value
- literal only, not a variable
- subscript keyPath: inside a closure
basics
~20 sA key-path literal such as .name converts to a (Contact) -> String function wherever one is expected, so map applies it to each element. Only the literal converts; a stored KeyPath value needs a closure: { $0[keyPath: path] }.
solid answer
~30 sA key-path expression like `\Contact.name` is normally a `KeyPath` object, but when the context expects a function `(Root) -> Value`, the compiler converts the **literal** into a closure equivalent to `{ $0[keyPath: \Contact.name] }`. That is why `map(\.name)`, `filter(\.isFavorite)`, `compactMap(\.email)` and `contains(where: \.isFavorite)` all work, and why `compactMap(\.self)` unwraps an array of optionals. The conversion applies only to the literal syntax: a constant `let path = \Contact.name` already has the type `WritableKeyPath<Contact, String>`, which is a class, not a function, so `map(path)` fails with `no exact matches in call to instance method 'map'`. Write `map { $0[keyPath: path] }` instead.
code
swift · 23 linesstruct Contact {
var name: String
var email: String?
var isFavorite: Bool
}
let contacts = [
Contact(name: "Ana", email: "[email protected]", isFavorite: true),
Contact(name: "Bo", email: nil, isFavorite: false),
]
let names = contacts.map(\.name) // ["Ana", "Bo"]
let favorites = contacts.filter(\.isFavorite) // [Ana]
let emails = contacts.compactMap(\.email) // ["[email protected]"]
let ids = [3, nil, 7].compactMap(\.self) // [3, 7]
let nameOf: (Contact) -> String = \.name // a key-path literal converts to a function
print(names, favorites.count, emails, ids, nameOf(contacts[1]))
let path = \Contact.name // a stored KeyPath value, not a literal
// contacts.map(path) // error: no exact matches in call to instance method 'map'
let viaSubscript = contacts.map { $0[keyPath: path] }
print(viaSubscript)go deeper
Recall that map(.name) means map { $0.name }, that filter needs a Bool path, and that compactMap(.self) drops nils.
Explain that the compiler converts a key-path literal into a (Root) -> Value closure, and that a stored key path is a class instance applied with the keyPath subscript.
Show where the literal and a closure diverge: subscript arguments captured at creation, and APIs that should take a function type so callers can pass either.
Frame the trade-off as readability: key-path literals shorten pipelines, but code that stores and passes key paths around needs explicit keyPath subscripts and clear parameter types.
## What a key-path expression is A **key-path expression** names a property or subscript of a type without naming an instance: `\Contact.name` means "the `name` of some `Contact`". At compile time it becomes an instance of one of the standard library's key-path classes, here `WritableKeyPath<Contact, String>`, and you apply it to a value with the built-in subscript `value[keyPath: path]`. The root type may be omitted when the context supplies it, so `\.name` is the same expression wherever the compiler already knows the root is `Contact`. ## The key-path-as-function conversion Swift also lets a key-path **literal** appear where a function is expected. A literal whose root is `Root` and whose path produces `Value` is accepted in place of a closure of type `(Root) -> Value`, and the compiler generates a closure equivalent to `{ $0[keyPath: \Root.value] }`. Everyday uses: - `contacts.map(\.name)` returns `[String]`, the same as `contacts.map { $0.name }`. - `contacts.filter(\.isFavorite)` works because the path produces a `Bool`, which is what `filter` needs. - `contacts.compactMap(\.email)` drops the contacts whose `email` is `nil`. - `contacts.contains(where: \.isFavorite)`, `first(where:)` and `allSatisfy(_:)` accept the same `Bool` paths. - `let nameOf: (Contact) -> String = \.name` stores the converted function in a constant of function type. The rule is about **types**, not about particular methods: any parameter of function type `(Root) -> Value` can take the literal, including your own functions. The value type must match what the function returns; `filter(\.name)` fails because `String` is not `Bool`. ## The identity key path, \.self `\.self` is the **identity key path**: its path is the whole value, so `\Contact.self` is a `WritableKeyPath<Contact, Contact>`. Converted to a function it is the identity function, which makes a few idioms read well: 1. `[3, nil, 7].compactMap(\.self)` returns `[3, 7]`, because the identity of an `Int?` is that optional, and `compactMap` drops the `nil`. 2. `[true, false].filter(\.self)` keeps the `true` elements. 3. `value[keyPath: \.self] = newValue` replaces a whole variable in one step. ## Why a stored KeyPath does not convert The conversion is defined for the **literal syntax only**. The type checker prefers a key-path type for `\Contact.name` but also allows a function type when the context demands one; once the literal has been bound to a constant, that choice is over. `let path = \Contact.name` has the class type `WritableKeyPath<Contact, String>`, and a class instance is not a function, so: ```swift struct Contact { var name: String } let contacts = [Contact(name: "Ana"), Contact(name: "Bo")] let path = \Contact.name // contacts.map(path) // error: no exact matches in call to instance method 'map' let names = contacts.map { $0[keyPath: path] } ``` A coercion does not help either: `path as (Contact) -> String` fails with `cannot convert value of type 'WritableKeyPath<Contact, String>' to type '(Contact) -> String' in coercion`. Code that receives key paths at run time, such as a column list or a configurable mapping, applies them with `[keyPath:]` inside a closure, or declares its own helper that takes a `KeyPath<Element, T>` parameter and does the same. | Form | Accepted where `(Contact) -> String` is expected? | |---|---| | `\.name` or `\Contact.name` written in place | yes, converted to a closure | | `{ $0.name }` | yes, an ordinary closure | | `let path = \Contact.name`, then `path` | no, it is a `WritableKeyPath` object | | `{ $0[keyPath: path] }` | yes, a closure applying the stored path | ## When the expression is evaluated A key-path expression is evaluated **once**, where it is written. If a subscript component contains a variable or a function call, its value is captured at that moment with value semantics: after `var i = 0; let path = \[String].[i]`, changing `i` to `1` does not move `path`, which still reads element `0`. A closure that reads `i` sees the new value. This is where the literal and a hand-written closure can behave differently, so a subscript index computed from mutable state belongs in a closure when it must follow that state. ## What to remember - The conversion turns a literal into a closure; the closure reads the property through the key path. - `\.self` is the identity path, handy with `compactMap` and `filter`. - A key path held in a variable is an object of a key-path class; apply it with `[keyPath:]`.
- Why does contacts.filter(\.name) fail to compile when contacts.filter(\.isFavorite) works?The literal converts to `(Contact) -> Value`, where `Value` is whatever the path produces. `filter` needs `(Contact) -> Bool`, so only a path ending in a `Bool` fits; `\.name` produces a `String`. Write the test as a closure, such as `filter { !$0.name.isEmpty }`.
- How do you let your own function accept either a key-path literal or a closure?Declare the parameter as a function type, for example `func column<T>(_ value: (Contact) -> T)`. Callers can then pass `\.name` or `{ $0.name.uppercased() }`. If you declare it as `KeyPath<Contact, T>` instead, callers must pass a key path, and a closure no longer fits.
- Why does var i = 0; let path = \[String].[i] keep reading index 0 after i changes?The subscript argument is evaluated once, when the key-path expression is evaluated, and stored in the key path by value. Later changes to `i` do not reach it. A closure `{ $0[i] }` captures the variable instead, so it reads the current value.
A key path is like a column heading in a spreadsheet: "Name" means nothing until you point it at a row, and the same heading works on every row. Handing map the heading means "read this column from each row"; a heading you saved on a sticky note still has to be read out by someone, which is the closure.
- A stored KeyPath constant can be passed anywhere a closure is expected.
- filter(\.name) works because any property can act as a predicate.
- \.self is a special case only allowed in SwiftUI's ForEach.
- A key path re-evaluates its subscript arguments every time it is applied.
- map has a dedicated KeyPath overload in the standard library.