KVC


Greetings, traveler!

KVC is a mechanism Cocoa provides that assists in accessing an object’s properties using string identifiers.

Example

Consider this example. Let’s create a class. Since KVC is connected with Objective-C, there are some limitations. Our class must inherit from the NSObject, and we need to mark its properties with the @objc dynamic attribute. We don’t have to add @objc to our class since inheriting from NSObject does that automatically.

final class Vehicle: NSObject {
    @objc dynamic var speed: Int = .zero
}

Now, we can access values this way.

let vehicle = Vehicle()
let key = "speed"
let speed = vehicle.value(forKey: key)
print(speed)

And set new values like this.

vehicle.setValue(200, forKey: key)
print(vehicle.speed)

Moreover, you can use a keyPath mechanism.

let speed = vehicle[keyPath: \.speed]
print(speed)

By the way, if you want to read more about the Swift keypaths, check out this article.

Conclusion

KVC is an Objective-C feature, so it can be challenging to use it in Swift, as the syntax can be cumbersome and unintuitive. In many cases, the Swift API does not map well to this mechanism, leading to awkwardly constructed code. However, there are specific options available in Swift that have been designed with KVC/KVO in mind, allowing for more seamless integration in your code. For example, we can use KVO with UIKit APIs. Wanna know more about that? Welcome to my following article, then.