I have been trying to figure this out for a while but cannot understand the advantage of KVC other than :
- Compiler checks (thus avoiding stringly typed code)
- Used with KVO
I am not sure if there is any advantage of using KVC other than the 2 cases said above (i know i might be wrong) but i could not find one !
Like consider the following code :
class Profile: NSObject {
@objc var firstName: String
var lastName: String
init(firstName: String,lastName: String) {
self.firstName = firstName
self.lastName = lastName
super.init()
}
}
let profile1 = Profile(firstName: "John", lastName: "Doe")
profile1.firstName // returns String "John"
profile1.value(forKey: "firstName") // returns Optional<Any>
let firstNameKey = \Profile.firstName
profile1[keyPath: firstNameKey] /* returns String "John" */
I mean why would i use :
let firstNameKey = \Profile.firstName
profile1[keyPath: firstNameKey] /* returns String "John" */
instead of :
profile1.firstName // returns String "John"
And if someone has some code sample/examples, then if they can explain it using swift , it would be great (as my Objective-C is not good)