Key paths

Swift language Mid-level Swift 5.2+ iOS 17+ Reviewed By Alok Singh

Pick the fix

Sorting with a key path in place of the comparator doesn't compile. Which works with only the standard library?

Options
Hint 1 of 1

What does sorted(by:) expect?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A people.sorted { $0.age < $1.age }

Correct. sorted(by:) needs a comparison closure.

Why not the others?
  • B people.sorted(\.age). No such overload exists in the standard library.
  • C people.sorted(by: \Person.age). A key path to Int isn't a (Person, Person) -> Bool comparator.
  • D people.sorted(using: KeyPathComparator(\.age)). This works, but it comes from Foundation (iOS 15+), not the standard library.

30-second answer

A key path (\Person.age) is a type-safe reference to a property that you can store and pass around, then read with person[keyPath: kp]. Key path expressions can be used where a function is expected, such as map(\.name). For sorting, use a closure or Foundation's KeyPathComparator.

Practise saying it · 30 s. No recording, just a timer

Explain key paths.

Say your answer out loud, then check which of these points you covered:

  • Type-safe property references
  • Key paths as functions in map
  • Comparators need closures or Foundation

Deep dive

WritableKeyPath and ReferenceWritableKeyPath allow writing.

people.map(\.name) works because key paths convert to functions (SE-0249).

SwiftUI uses key paths for environment values, bindings and ForEach(id:).

KeyPathComparator(\.age) with sorted(using:) comes from Foundation.

Common mistakes

  • Expecting a key path to work as a comparator.
  • Using strings (KVC) instead of key paths in Swift.

Senior take & follow-ups

Seniors know where key-path-as-function applies and where it doesn't.

Follow-up questions

Think of your answer first, then open the hint.

  1. How would you write a sorted-by-key-path helper?

    Show hint

    An extension taking KeyPath<Element, T> where T: Comparable.

  2. What is a ReferenceWritableKeyPath?

    Show hint

    A writable key path into a class instance.

Suggest a fix if something here is wrong or out of date.