Key-Path Expressions: Type-Safe Pointers to Properties

A key path is a type-safe "pointer" to a property, like `\User.name`. It lets you pass around a reference to a property itself, not just its value, making it ideal for generic sorting or SwiftUI data binding. The footgun is forgetting they are strictly typed.
WHY IT EXISTS: Swift needed a way to refer to properties dynamically without using unsafe, string-based keys like in older languages. Direct property access is great, but sometimes you need to pass a reference to the property itself. Key paths provide this mechanism in a type-safe, compile-time-checked way.
THE MENTAL MODEL: Think of a key path as a pre-compiled, reusable "getter" or "setter" for a property. It's a blueprint for access. It's like having a specific GPS route that you can give to any driver (any instance of an object), and they'll know exactly how to get to the specific location (the property value) without looking up directions each time.
HOW IT WORKS: You create a key path by prefixing a property access chain with a backslash, like \User.profile.email. The compiler verifies this path is valid for the User type and creates an instance of a KeyPath generic type, such as KeyPath<User, String>. You can then use this key path object with an instance of User to get or set the value: user[keyPath: emailKeyPath] = "new@email.com". The type safety ensures you can't accidentally use a String key path on an Int property.
WHEN TO USE IT: Key paths shine when building generic APIs. They are heavily used in SwiftUI for data binding (e.g., TextField("Name", text: $user.name)), in sorting and filtering collections without writing repetitive code (e.g., users.sorted(by: \.lastName)), and for configuring UI components dynamically. They allow you to write code that operates on properties without knowing their specific names at compile time.
WHEN NOT TO USE IT: For simple, direct property access, just use dot notation (user.name). It's more direct, easier to read for simple cases, and slightly more performant. Key paths introduce a layer of indirection that is unnecessary if you already have the object and know exactly which property you need. Don't over-abstract if you don't need the flexibility.
ONE CANONICAL EXAMPLE: Sorting a collection by different properties is a classic use case. Instead of writing separate sort functions for first name, last name, and age, you can use key paths. The sorted(by:) method on sequences can take a key path directly. For a users array, you can sort it with users.sorted(by: \.age) or users.sorted(by: \.lastName), reusing the same sorting logic with different type-safe property references.
Read the original → developer.apple.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.