Keypaths trong Swift

Tram Ho

Terms

keypath : Read-only access to properties.

writablekeypath : read-write access to value type properties.

referencewriteablekeypath : read-write access to a reference type property.

What is Keypath?

A keypath provides read-only access to a property, while a writable keypath provides writable access to a property.
For example:
Perhaps the best way to describe how to access this keypath is through an example where we have a struct object:

We can then access these properties through WritableKeyPath<Person, String> or WritableKeyPath<Person, Int> (where firstname and secondname are of type String and age is of type Int ).

The results we have are:

With WritableKeyPath access we can store the following properties:

This means that we have the potential to use the same property in many different places and store them as one property.

Belongs to each other

The following is an example of the keypaths that are intertwined

Ingredients of keypath

Swift gives us the flexibility to coordinate keypaths at runtime

Keypath as Erasable Variable We can use a keypath on a reference type (eg class).

Limit of keypath

The key path cannot refer to the static member 'lifeform'.

If we change Person to have a static variable.

And..

What if we want to use KVO? We'll need to call a keypath when using the func observe<Value>(_ keyPath: KeyPath<ViewController, Value>, options: NSKeyValueObservingOptions = [], changeHandler: @escaping (ViewController, NSKeyValueObservedChange<Value>) -> Void) -> NSKeyValueObservation function func observe<Value>(_ keyPath: KeyPath<ViewController, Value>, options: NSKeyValueObservingOptions = [], changeHandler: @escaping (ViewController, NSKeyValueObservedChange<Value>) -> Void) -> NSKeyValueObservation as follows:

Conclude

Keypaths are really useful in iOS programming as well as related to Combine and SwiftUI as well as KVO.
I hope this short article has become familiar with this feature in Swift.

reference: https://stevenpcurtis.medium.com/what-are-swifts-keypaths-e8c829bc97d3

Share the news now

Source : Viblo