What are Swift’s Keypaths?
Difficulty: Beginner | Easy | Normal | Challenging
This article has been developed using Xcode 11.4.1, and Swift 5.2.2
keypath: Read-only access to a property
writablekeypath: read-write access to a value-type property
referencewritablekeypath: read-write access to a reference-type property
ReferenceWritableKeyPath<Root, Bool> in the assign function
which is the one that allows us to connect to
UIKit elements, for example
That seems fine, but what are keypaths? How are they used, and what do they mean?
Could you make an article explaining this for me?
I don’t mind if I do!
What is a keypath?
A keypath provides read-only access to a property, whilst a writable keypath provides (well…) writable access to a property.
A keypath example
Perhaps the best way to describe this access is through an example, where we can set up a rather basic
we can then access the properties through
WritableKeyPath<Person, String> or
WritableKeyPath<Person, Int> (where firstname and secondname are represented by a
String and age is represeted by a
The following keypath therefore returns a
String, and that can be printed out
Now even the property type can be stored
which means that you can potentially use the same property in multiple places, and storing it as a property itself means that it would only need to be stored in one place.
The following is an example of nested keypaths
Swift allows you to dynamically combine keypaths at runtime (of course the types need to be compatible).
KeyPaths as type-erased variants
You may wish to have a keypath that does not require the Value parameter
drawerSocks can be stored with the same type:
Value parameter has been type-erased.
KeyPaths of reference types
This shouldn’t be a too big surprise, but if you use a keypath on a reference type (for example a
Are keypaths new?
Keypaths have been around for some time, they’re present in
Objective-C! However, they were not type safe (
keyPath() is actually a
Key path cannot refer to static member 'lifeform'
If we change
Person to have a static var.
As, well, keypaths cannot refer to static members! What a shame!
Want to use KVO in your code? You’re going to need to call a keypath when you use
func observe<Value>(_ keyPath: KeyPath<ViewController, Value>, options: NSKeyValueObservingOptions = , changeHandler: @escaping (ViewController, NSKeyValueObservedChange<Value>) -> Void) -> NSKeyValueObservation, and a sample implementation might look something like the following:
So consider yourself TOLD!
So, keypaths are actually useful in iOS development, being relevant for
Combine and SwiftUI as well as
Do you want to buckle up and become familiar with this, or not? I'd say understanding what you need to do is important- and you can read up
UIKit on this HERE.
I hope that this article has helped you out in become more familar in this relatively new feature of Swift.
If you’ve any questions, comments or suggestions please hit me up on Twitter