CODEX
Swift: Key Path Basics
Learn what KeyPaths are and how you can use them.
Keypaths in Swift
Keypaths offer a dynamic and type-safe way of referencing properties of a type.
KeyPath<ObjectType, PropertyType>
A key path is a reference to a property, not to the value of the property.
In practice, key paths allow you to refer to the same property in multiple places using the same key path variable. If you want to change the property you need to change it only in one place.
Retrieving and Modifying Properties with Key Paths
You can use key paths to retrieve and modify the values of properties.
As an example, let’s say you have a structure Fruit
:
struct Fruit {
var name: String
var color: String
}
You can obtain a reference to the name
property of the Fruit
structure by defining a key path:
let keyPath = \Fruit.name
But what can you do with it?
You can use this keyPath
reference as a subscript to a Fruit
instance to retrieve its name
:
var banana = Fruit(name: "Banana", color: "Yellow")