0Pricing
Swift Academy · Lesson

Using KeyPaths in Collections

Sort and map collections by key path.

Key Paths Shine in Collections

Collection operations like map, sorted, and filter often just read one property of each element. Key paths let you express that intent without writing a closure.

Swift accepts a key path anywhere a single-argument function returning a value is expected, because a key path can be used as a function from Root to Value.

struct Person {
    let name: String
    let age: Int
}

let people = [Person(name: "Ana", age: 30), Person(name: "Ben", age: 25)]
let names = people.map(\.name)
print(names)

map with Key Path Shorthand

Passing map(\.property) is equivalent to writing a closure that returns that property, but shorter and clearer. The leading backslash and dot let the compiler infer the element type.

Compare the two forms below; they produce the same result.

struct Person {
    let name: String
    let age: Int
}

let people = [Person(name: "Ana", age: 30), Person(name: "Ben", age: 25)]
let closureForm = people.map { $0.age }
let keyPathForm = people.map(\.age)
print(closureForm)
print(keyPathForm)

All lessons in this course

  1. KeyPath Basics
  2. Using KeyPaths in Collections
  3. Writable and Reference KeyPaths
  4. @dynamicMemberLookup
← Back to Swift Academy