# Swift Key Paths (\Person.name): KeyPath, map(\.name), and Sorting

Source: https://devdocs10.com/articles/swift/swift-keypaths  
By Murat Bo · Updated 2026-10-28 · DevDocs10 (https://devdocs10.com)

A Swift key path is a value that points to a property, written with a backslash: `\Person.name` means "the `name` property of a `Person`". You read through it with `person[keyPath: \Person.name]`, pass it where a function is expected, as in `users.map(\.name)`, and write through it when the property is mutable. The compiler checks every key path, so a misspelled property is a build error, not a runtime crash. This guide covers the three key path types, key paths as functions, sorting by a key path, nested and optional paths, dynamic member lookup, and key paths under Swift 6 concurrency checking.

> **Difficulty:** Intermediate
>
> **Helpful to know first:** structs and classes, closures such as `map { $0.name }`, and how a generic function uses a placeholder type like `<Value>`.

## What \Person.name Actually Is

A key path stores a route to a property, not the property's value. `\Person.name` knows how to get from any `Person` to its `name`. You apply it to a particular person later, with the `[keyPath:]` subscript that every Swift type has.

```swift
struct Person {
    var name: String
    var age: Int
}

let nameKey = \Person.name        // a key path value, not a String
let ada = Person(name: "Ada", age: 36)

print(ada[keyPath: nameKey])      // Output: Ada
print(type(of: nameKey))          // Output: WritableKeyPath<Person, String>
print(nameKey)                    // Output: \Person.name
```

Output (tested with Swift 6.4):

```text
Ada
WritableKeyPath<Person, String>
\Person.name
```

The type says everything about the path: it starts at a `Person` (the root), ends at a `String` (the value), and can write as well as read. The leading backslash is what turns `Person.name` into a key path; without it, Swift reads the line as a property access on the type and reports an error. When Swift already knows the root type from context, you can leave it out and write `\.name`.

A key path is an ordinary value. You can store it in a variable, pass it to a function, put it in an array, or compare two of them. That is the problem it solves: code that needs to know *which* property to use, chosen by the caller, while keeping full type checking.

## KeyPath, WritableKeyPath, and ReferenceWritableKeyPath

The compiler picks the key path type from the property and from the kind of type that owns it. You never choose it by hand; you choose which of them your functions accept.

```swift
struct Account {
    let id: Int
    var email: String
    var isVerified: Bool { !email.isEmpty }
}

final class Session {
    var token = ""
}

print(type(of: \Account.id))          // Output: KeyPath<Account, Int>
print(type(of: \Account.email))       // Output: WritableKeyPath<Account, String>
print(type(of: \Account.isVerified))  // Output: KeyPath<Account, Bool>
print(type(of: \Session.token))       // Output: ReferenceWritableKeyPath<Session, String>
```

Output (tested with Swift 6.4):

```text
KeyPath<Account, Int>
WritableKeyPath<Account, String>
KeyPath<Account, Bool>
ReferenceWritableKeyPath<Session, String>
```

| Type | You get it for | Can write? |
| --- | --- | --- |
| `KeyPath<Root, Value>` | `let` properties, computed properties without a setter, paths with `?.` | No |
| `WritableKeyPath<Root, Value>` | `var` properties of structs and enums | Yes, through a `var` root |
| `ReferenceWritableKeyPath<Root, Value>` | `var` properties of classes | Yes, even through a `let` reference |
| `PartialKeyPath<Root>` | Any key path from `Root`, value type erased to `Any` | No |
| `AnyKeyPath` | Any key path at all | No |

The types form a class hierarchy: `ReferenceWritableKeyPath` is a subclass of `WritableKeyPath`, which is a subclass of `KeyPath`, which in turn is a `PartialKeyPath` and an `AnyKeyPath`. So a function that only reads should accept `KeyPath`; it then works with all three of the first rows.

Writing follows the same rules as writing the property directly. A struct is a value, so its root must be a `var`. A class instance is shared, so a `let` reference is enough:

```swift
struct Account {
    var email: String
}

final class Session {
    var token = ""
}

var account = Account(email: "old@example.com")
account[keyPath: \.email] = "new@example.com"
print(account.email)      // Output: new@example.com

let session = Session()   // a let reference
session[keyPath: \.token] = "abc123"
print(session.token)      // Output: abc123
```

Output (tested with Swift 6.4):

```text
new@example.com
abc123
```

If `account` were a `let`, the write would fail with `cannot assign through subscript: 'account' is a 'let' constant`. The reason is value versus reference semantics, explained in [Swift value vs reference semantics](/articles/swift/swift-value-vs-reference-semantics).

## Key Paths in Everyday Swift Code

### Key paths as functions: map(\.name) and filter(\.isActive)

Since Swift 5.2, a key path literal can be used wherever a function from the root to the value is expected. `\.name` becomes `{ $0.name }`, and a key path to a `Bool` works as a filter condition.

```swift
struct User {
    var name: String
    var isActive: Bool
}

let users = [
    User(name: "Ada", isActive: true),
    User(name: "Bo", isActive: false),
    User(name: "Cy", isActive: true),
]

print(users.map(\.name))                      // Output: ["Ada", "Bo", "Cy"]
print(users.filter(\.isActive).map(\.name))   // Output: ["Ada", "Cy"]
print(users.contains(where: \.isActive))      // Output: true
print(users.map(\.name.count))                // Output: [3, 2, 2]
```

Output (tested with Swift 6.4):

```text
["Ada", "Bo", "Cy"]
["Ada", "Cy"]
true
[3, 2, 2]
```

The last line shows that a path can go through several properties: the `count` of each user's `name`. This conversion only applies to a key path written directly in the call; a key path stored in a constant is not converted (see Common Mistakes). The methods themselves are covered in [Swift map, filter, and sorted](/articles/swift/swift-collection-map-filter-sorted).

### Sorting by a key path

The standard library's `sorted(by:)` takes a comparison of two elements, so it cannot take a key path. A five-line extension adds a key path version that works for any `Comparable` property:

```swift
extension Sequence {
    func sorted<Value: Comparable>(by keyPath: KeyPath<Element, Value>) -> [Element] {
        sorted { $0[keyPath: keyPath] < $1[keyPath: keyPath] }
    }
}

struct Product {
    var name: String
    var price: Double
}

let products = [
    Product(name: "Lamp", price: 39.0),
    Product(name: "Desk", price: 120.0),
    Product(name: "Chair", price: 85.5),
]

print(products.sorted(by: \.price).map(\.name))   // Output: ["Lamp", "Chair", "Desk"]
print(products.sorted(by: \.name).map(\.name))    // Output: ["Chair", "Desk", "Lamp"]
```

Output (tested with Swift 6.4):

```text
["Lamp", "Chair", "Desk"]
["Chair", "Desk", "Lamp"]
```

On Apple platforms (macOS 12, iOS 15 and later), Foundation also has `KeyPathComparator`, which adds descending order and sorting by several keys without any extension:

```swift
import Foundation

struct Product {
    var name: String
    var price: Double
}

let products = [
    Product(name: "Lamp", price: 39.0),
    Product(name: "Desk", price: 120.0),
    Product(name: "Chair", price: 85.5),
]

let cheapestFirst = products.sorted(using: KeyPathComparator(\.price))
let byNameDescending = products.sorted(using: KeyPathComparator(\.name, order: .reverse))

print(cheapestFirst.map(\.name))      // Output: ["Lamp", "Chair", "Desk"]
print(byNameDescending.map(\.name))   // Output: ["Lamp", "Desk", "Chair"]
```

Output (tested with Swift 6.4):

```text
["Lamp", "Chair", "Desk"]
["Lamp", "Desk", "Chair"]
```

To sort by a second key when the first is equal, pass an array: `sorted(using: [KeyPathComparator(\.price), KeyPathComparator(\.name)])`.

### One helper for every numeric property

Key paths let one generic function do a job that would otherwise need a copy per property. This `sum(of:)` adds up any numeric property of any element type:

```swift
extension Sequence {
    func sum<Value: AdditiveArithmetic>(of keyPath: KeyPath<Element, Value>) -> Value {
        reduce(.zero) { $0 + $1[keyPath: keyPath] }
    }
}

struct LineItem {
    var quantity: Int
    var price: Double
}

let cart = [LineItem(quantity: 2, price: 9.5), LineItem(quantity: 1, price: 20.0)]

print(cart.sum(of: \.quantity))   // Output: 3
print(cart.sum(of: \.price))      // Output: 29.5
```

Output (tested with Swift 6.4):

```text
3
29.5
```

The result type follows the key path: `Int` for `\.quantity`, `Double` for `\.price`. Passing a key path to a `String` property does not compile, because `String` is not `AdditiveArithmetic`. More on such constraints in [Swift generics](/articles/swift/swift-generics-functions-types).

### Writing through a key path: one update method for many fields

A `WritableKeyPath` parameter lets the caller choose which property to change. This `with(_:_:)` method returns a modified copy, so settings can be built in one expression:

```swift
struct Settings {
    var volume = 5
    var theme = "light"
    var notifications = true
}

extension Settings {
    func with<Value>(_ keyPath: WritableKeyPath<Settings, Value>, _ value: Value) -> Settings {
        var copy = self
        copy[keyPath: keyPath] = value
        return copy
    }
}

let custom = Settings().with(\.volume, 8).with(\.theme, "dark")
print(custom.volume, custom.theme, custom.notifications)   // Output: 8 dark true
```

Output (tested with Swift 6.4):

```text
8 dark true
```

The `Value` type comes from the key path, so the value must match it: `.with(\.volume, "loud")` fails with `cannot convert value of type 'String' to expected argument type 'Int'`.

### Nested, optional, and subscript key paths

A key path can follow several properties, pass through an optional with `?.`, include a subscript, and be joined to another path with `appending(path:)`.

```swift
struct Address {
    var city: String
}

struct Customer {
    var name: String
    var address: Address
    var backup: Address?
    var tags: [String]
}

let customer = Customer(name: "Ada", address: Address(city: "London"), backup: nil, tags: ["vip"])

print(customer[keyPath: \.address.city])          // Output: London
print(customer[keyPath: \.backup?.city] as Any)   // Output: nil
print(customer[keyPath: \.tags[0]])               // Output: vip
print(type(of: \Customer.backup?.city))           // Output: KeyPath<Customer, Optional<String>>

let addressPath = \Customer.address
let cityPath = addressPath.appending(path: \.city)
print(customer[keyPath: cityPath])                // Output: London
```

Output (tested with Swift 6.4):

```text
London
nil
vip
KeyPath<Customer, Optional<String>>
London
```

Going through an optional makes the value optional and the path read-only, even though every property on the way is a `var`. A subscript inside a key path runs when you use the path, so `\.tags[0]` on an empty array crashes exactly like `tags[0]`. The special path `\.self` refers to the whole value.

### Dynamic member lookup with key paths

With `@dynamicMemberLookup`, a wrapper type can expose the properties of the value it wraps. When the subscript takes a key path, every access is still type-checked. This wrapper records each change:

```swift
struct Settings {
    var volume = 5
    var theme = "light"
}

@dynamicMemberLookup
struct Logged<Value> {
    private(set) var value: Value
    private(set) var changes: [String] = []

    init(_ value: Value) {
        self.value = value
    }

    subscript<T>(dynamicMember keyPath: WritableKeyPath<Value, T>) -> T {
        get { value[keyPath: keyPath] }
        set {
            changes.append("\(keyPath) = \(newValue)")
            value[keyPath: keyPath] = newValue
        }
    }
}

var settings = Logged(Settings())
settings.volume = 8
settings.theme = "dark"
print(settings.volume)   // Output: 8

for change in settings.changes {
    print(change)
}
// Output:
// \Settings.volume = 8
// \Settings.theme = dark
```

Output (tested with Swift 6.4):

```text
8
\Settings.volume = 8
\Settings.theme = dark
```

`settings.volume` compiles because Swift rewrites it as `settings[dynamicMember: \Settings.volume]`; a typo such as `settings.volum` is still a compile error. SwiftUI uses the same technique: `$model.name` turns a binding to a model into a binding to one of its properties.

## How Key Paths Behave in Detail

### Key paths are Hashable, and PartialKeyPath mixes value types

Two key paths to the same property are equal, so key paths can be dictionary keys or `Set` elements. To keep paths with different value types in one array, store them as `PartialKeyPath<Root>`; reading through one gives `Any`.

```swift
struct Person {
    var name: String
    var age: Int
}

let columns: [(title: String, path: PartialKeyPath<Person>)] = [
    ("Name", \Person.name),
    ("Age", \Person.age),
]

let ada = Person(name: "Ada", age: 36)
for column in columns {
    print("\(column.title): \(ada[keyPath: column.path])")
}
// Output:
// Name: Ada
// Age: 36

print(\Person.name == \Person.name)   // Output: true
```

Output (tested with Swift 6.4):

```text
Name: Ada
Age: 36
true
```

### There is no "any KeyPath"

`KeyPath` is a generic class, not a protocol, so the `any` keyword does not apply to it. `let path: any KeyPath<Person, String>` fails with `'any' has no effect on concrete type 'KeyPath<Person, String>'`. When you need type erasure, the class hierarchy already provides it: `PartialKeyPath<Root>` and `AnyKeyPath`. You may still see `any KeyPath<Person, String> & Sendable` in Swift 6 compiler messages; there `any` applies to the combination with the `Sendable` protocol, which is valid. The `any` keyword itself is explained in [Swift existentials](/articles/swift/swift-existentials-any-self).

### Key paths cannot point to methods

A key path can name a stored property, a computed property such as `\String.count`, or a subscript. It cannot name a method: `\String.uppercased()` fails with `key path cannot refer to instance method 'uppercased()'`. Use a closure, `{ $0.uppercased() }`, when the value comes from a method call.

### Key paths and Sendable in Swift 6

In the Swift 6 language mode, values that cross between tasks and actors must be `Sendable`. The key path classes are not `Sendable` in general, because a key path can capture subscript arguments. A key path *literal* whose parts are all `Sendable` is inferred as `Sendable`, so `static let sortKey = \Person.name` compiles. Writing the type out as `KeyPath<Person, String>` drops that information, and Swift 6 rejects a `static let` declared that way with `static property 'sortKey' is not concurrency-safe because non-'Sendable' type 'KeyPath<Person, String>' may have shared mutable state`. The fix is to spell the type as `KeyPath<Person, String> & Sendable`, shown with a stored property in Common Mistakes below. For the rules behind this, see [Swift Sendable and isolation](/articles/swift/swift-sendable-mainactor-isolation).

## Predict the Output

Snippet 1. What does this print?

```swift
struct Item {
    var name: String
    var tags: [String]
}

let items = [Item(name: "pen", tags: ["office"]), Item(name: "cup", tags: [])]
print(items.map(\.tags.count))
print(items.map(\.name.first))
```

Output (tested with Swift 6.4):

```text
[1, 0]
[Optional("p"), Optional("c")]
```

**Answer:**

It prints `[1, 0]` and then `[Optional("p"), Optional("c")]`.

Both paths go two properties deep. `tags.count` is a plain `Int`. `name.first` is a `Character?`, because a string can be empty, so the key path's value type is optional and `map` returns an array of optionals.

Snippet 2. What does this print?

```swift
final class Box {
    var value = 1
}

let box = Box()
let path = \Box.value
box[keyPath: path] += 10
print(type(of: path), box.value)
```

Output (tested with Swift 6.4):

```text
ReferenceWritableKeyPath<Box, Int> 11
```

**Answer:**

It prints `ReferenceWritableKeyPath<Box, Int> 11`.

Many people expect an error because `box` is a `let`. But `Box` is a class: `let` fixes the reference, not the object it points to. The key path to a class's `var` property is a `ReferenceWritableKeyPath`, which can write through a `let` reference, and `+=` works through the subscript like any other assignment.

## Common Mistakes with Swift Key Paths

### Writing Person.name without the backslash

The backslash is easy to lose, especially when code is copied through tools that treat it as an escape character.

**Problem:** Without the backslash, `Person.name` is an attempt to read an instance property from the type itself. The compiler reports `instance member 'name' cannot be used on type 'Person'; did you mean to use a value of this type instead?`

```swift
struct Person {
    var name: String
}

let path = Person.name
```

**Fix:** Start every key path with a backslash.

```swift
struct Person {
    var name: String
}

let path = \Person.name
print(Person(name: "Ada")[keyPath: path])   // Output: Ada
```

Output (tested with Swift 6.4):

```text
Ada
```

The corrected version works because the backslash tells Swift to build a key path value instead of evaluating a property.

### Passing a key path to sorted(by:)

Because `map(\.name)` works, it is natural to expect `sorted(by: \.price)` to work as well.

**Problem:** `sorted(by:)` needs a function that compares two elements, and a key path only converts to a function of one element. The compiler reports `cannot infer key path type from context; consider explicitly specifying a root type` and `cannot convert key path into a multi-argument function type '(Product, Product) throws -> Bool'`.

```swift
struct Product {
    var name: String
    var price: Double
}

let products = [Product(name: "Desk", price: 120.0), Product(name: "Lamp", price: 39.0)]
let cheapestFirst = products.sorted(by: \.price)
```

**Fix:** Write the comparison, or add the key path `sorted(by:)` extension shown earlier.

```swift
struct Product {
    var name: String
    var price: Double
}

let products = [Product(name: "Desk", price: 120.0), Product(name: "Lamp", price: 39.0)]
let cheapestFirst = products.sorted { $0.price < $1.price }
print(cheapestFirst.map(\.name))   // Output: ["Lamp", "Desk"]
```

Output (tested with Swift 6.4):

```text
["Lamp", "Desk"]
```

The corrected version works because the closure takes two products and returns whether the first belongs before the second.

### Passing a stored key path where a function is expected

The key-path-as-function conversion applies to key path literals only.

**Problem:** `namePath` is a `KeyPath` value, not a literal, so it is not converted to a function. The compiler reports `no exact matches in call to instance method 'map'`.

```swift
struct User {
    var name: String
}

let users = [User(name: "Ada"), User(name: "Bo")]
let namePath = \User.name
print(users.map(namePath))
```

**Fix:** Apply the stored key path inside a closure.

```swift
struct User {
    var name: String
}

let users = [User(name: "Ada"), User(name: "Bo")]
let namePath = \User.name
print(users.map { $0[keyPath: namePath] })   // Output: ["Ada", "Bo"]
```

Output (tested with Swift 6.4):

```text
["Ada", "Bo"]
```

The corrected version works because the closure is a real function, and the `[keyPath:]` subscript accepts any key path value.

### Passing a read-only property where a WritableKeyPath is required

A function that writes through a key path can only accept properties that can be written.

**Problem:** `isVerified` is a computed property without a setter, so `\.isVerified` is a `KeyPath`. The compiler reports `cannot convert value of type 'KeyPath<Account, Bool>' to expected argument type 'WritableKeyPath<Account, Bool>'`; in the Swift 6 language mode the same error names the type as `'any KeyPath<Account, Bool> & Sendable'`.

```swift
struct Account {
    var email: String
    var isVerified: Bool { !email.isEmpty }
}

func reset<Value>(_ account: inout Account, _ keyPath: WritableKeyPath<Account, Value>, to value: Value) {
    account[keyPath: keyPath] = value
}

var account = Account(email: "a@example.com")
reset(&account, \.isVerified, to: false)
```

**Fix:** Change the stored property that the computed one depends on.

```swift
struct Account {
    var email: String
    var isVerified: Bool { !email.isEmpty }
}

func reset<Value>(_ account: inout Account, _ keyPath: WritableKeyPath<Account, Value>, to value: Value) {
    account[keyPath: keyPath] = value
}

var account = Account(email: "a@example.com")
reset(&account, \.email, to: "")
print(account.isVerified)   // Output: false
```

Output (tested with Swift 6.4):

```text
false
```

The corrected version works because `email` is a stored `var`, so its key path is writable, and `isVerified` follows from it.

### Storing a key path in a Sendable type without & Sendable

Types that are passed between tasks often keep a key path, for example a sort rule.

**Problem:** The property's type is `KeyPath<Person, String>`, which is not `Sendable`. In the Swift 6 language mode this is an error: `stored property 'key' of 'Sendable'-conforming struct 'SortRule' has non-Sendable type 'KeyPath<Person, String>'`. In Swift 5 mode it is a warning that ends with "this is an error in the Swift 6 language mode".

```swift
struct Person: Sendable {
    var name: String
}

struct SortRule: Sendable {
    let key: KeyPath<Person, String>
}
```

**Fix:** Require a `Sendable` key path in the type.

```swift
struct Person: Sendable {
    var name: String
}

struct SortRule: Sendable {
    let key: KeyPath<Person, String> & Sendable
}

let rule = SortRule(key: \.name)
print(rule.key)   // Output: \Person.name
```

Output (tested with Swift 6.4):

```text
\Person.name
```

The corrected version works because the literal `\.name` is inferred as `Sendable`, and the property type now keeps that guarantee.

## Find the Bug

This generic helper should apply a 10% discount to whichever price field the caller names. It compiles, but the prices do not change. Why?

```swift
struct Order {
    var id: Int
    var price: Double
}

func applyDiscount(to orders: [Order], on field: WritableKeyPath<Order, Double>) -> [Order] {
    var result = orders
    for var order in result {
        order[keyPath: field] *= 0.9
    }
    return result
}

let orders = [Order(id: 1, price: 100), Order(id: 2, price: 50)]
print(applyDiscount(to: orders, on: \.price).map(\.price))
```

Output (tested with Swift 6.4):

```text
[100.0, 50.0]
```

**Answer:**

It prints `[100.0, 50.0]`. `Order` is a struct, so `for var order in result` gives the loop a copy of each element. The key path writes to that copy, which is thrown away at the end of each pass, and `result` is never changed. The compiler even hints at it with the warning `variable 'result' was never mutated; consider changing to 'let' constant`.

Write through the array element itself, using its index:

```swift
struct Order {
    var id: Int
    var price: Double
}

func applyDiscount(to orders: [Order], on field: WritableKeyPath<Order, Double>) -> [Order] {
    var result = orders
    for index in result.indices {
        result[index][keyPath: field] *= 0.9
    }
    return result
}

let orders = [Order(id: 1, price: 100), Order(id: 2, price: 50)]
print(applyDiscount(to: orders, on: \.price).map(\.price))   // Output: [90.0, 45.0]
```

Output (tested with Swift 6.4):

```text
[90.0, 45.0]
```

A `WritableKeyPath` changes exactly the value you apply it to. With structs, make sure that value is the one you keep.

## When to Use a Key Path, a Closure, or #keyPath

| You need | Use |
| --- | --- |
| To name one property to read: `map`, `filter`, sort helpers, table columns | A key path such as `\.name` |
| To let a caller choose a property to change | `WritableKeyPath` or `ReferenceWritableKeyPath` |
| To compute something (`$0.price * 1.2`), compare two values, or call a method | A closure |
| A string key for Objective-C KVC or KVO | `#keyPath(...)` or `value(forKey:)` |

A key path is the better choice when the caller's intent is "this property": it is shorter at the call site, it can be stored and compared, and it cannot accidentally do more than read a property. A closure is the better choice for anything that is not a plain property. `#keyPath(Person.name)` is something else: it produces the `String` `"name"` for Objective-C APIs and only works with `@objc` properties; see [Swift KVC, KVO, and dynamic](/articles/swift/swift-kvc-kvo-dynamic).

## Interview Questions About Swift Key Paths

### How do KeyPath, WritableKeyPath, and ReferenceWritableKeyPath differ?

`KeyPath` can only read. `WritableKeyPath` can also write to a mutable property of a value type, through a `var` root. `ReferenceWritableKeyPath` writes to a mutable property of a class and works through a `let` reference. The compiler picks the type from the property and its owner, and each type is a subclass of the one before.

### Why can you write users.map(\.name)?

Since Swift 5.2, a key path literal of type `KeyPath<Root, Value>` is implicitly converted to a function `(Root) -> Value` where one is expected. The conversion only applies to literals, not to key paths stored in variables.

### How is \Person.name different from #keyPath(Person.name)?

`\Person.name` is a typed Swift key path value that works with any Swift type. `#keyPath(Person.name)` is checked by the compiler but produces a plain `String` for Objective-C key-value coding, and requires an `@objc` property of an `NSObject` subclass.

## Try It Yourself

Build a small report that groups employees by whichever text property the caller chooses.

- Define `Employee` with `name`, `team` and `city`, all `String`.
- Write `report(_:by:)` that takes an array of employees and a `KeyPath<Employee, String>`.
- Group the employees by that property, then print one line per group, sorted by the group name: the group, the number of people, and their names.
- Call it once with `\.team` and once with `\.city`, printing `--` between the two reports.

**Expected output:** five lines: `Mobile (2): Ada, Cy`, `Web (1): Bo`, `--`, `Berlin (2): Bo, Cy`, and `London (1): Ada`.

**Hint:** `Dictionary(grouping:by:)` takes a closure; apply the key path inside it with `$0[keyPath: keyPath]`.

**Solution:**

```swift
struct Employee {
    var name: String
    var team: String
    var city: String
}

func report(_ employees: [Employee], by keyPath: KeyPath<Employee, String>) {
    let groups = Dictionary(grouping: employees) { $0[keyPath: keyPath] }
    for (key, members) in groups.sorted(by: { $0.key < $1.key }) {
        let names = members.map(\.name)
        print("\(key) (\(names.count)): \(names.joined(separator: ", "))")
    }
}

let staff = [
    Employee(name: "Ada", team: "Mobile", city: "London"),
    Employee(name: "Bo", team: "Web", city: "Berlin"),
    Employee(name: "Cy", team: "Mobile", city: "Berlin"),
]

report(staff, by: \.team)
print("--")
report(staff, by: \.city)
// Output:
// Mobile (2): Ada, Cy
// Web (1): Bo
// --
// Berlin (2): Bo, Cy
// London (1): Ada
```

Output (tested with Swift 6.4):

```text
Mobile (2): Ada, Cy
Web (1): Bo
--
Berlin (2): Bo, Cy
London (1): Ada
```

## Summary

- A key path such as `\Person.name` is a typed, checked reference to a property; apply it with `value[keyPath: path]`, and never drop the backslash.
- The compiler picks `KeyPath` (read-only), `WritableKeyPath` (struct `var`) or `ReferenceWritableKeyPath` (class `var`); accept the narrowest one your function needs.
- Key path literals work as functions: `map(\.name)`, `filter(\.isActive)`. Stored key paths and two-argument functions such as `sorted(by:)` need a closure or a small extension.
- Paths can be nested, go through optionals (and become read-only), include subscripts, and be joined with `appending(path:)`.
- Key paths are `Hashable`; use `PartialKeyPath` to mix value types, since `any KeyPath` is not valid.
- In Swift 6 mode, write `KeyPath<Root, Value> & Sendable` when a key path is stored in a `Sendable` type.

Key path helpers are generic functions at heart. Next, read [Swift generics for functions and types](/articles/swift/swift-generics-functions-types) to write your own helpers like `sum(of:)` with the right constraints.
