I can't get key-value chaining (KVC) to work in Swift for compound dot paths

357 Views Asked by At

Consider the following class, which can be executed in the Xcode Playground:

import Foundation
class MyClass : NSObject {

    var stringProperty:String
    var integerProperty:Int
    var linkedInstance:MyClass!

    init(String string:String, Int int:Int) {
        stringProperty = string
        integerProperty = int
    }
}

The following lines work as expected.

var myInstance = MyClass(String: "xxx", Int: 32)
myInstance.valueForKey("stringProperty")
myInstance.setValue(2, forKey: "integerProperty")
myInstance.valueForKey("integerProperty")

var anotherInstance = MyClass(String: "yyy", Int: 33)
myInstance.linkedInstance = anotherInstance
myInstance.linkedInstance.integerProperty = 2

However trying to access the value using KVC via a compound path,

myInstance.valueForKey("linkedInstance.integerProperty")

causess the error "Execution was interrupted, reason signal SIGABRT." I have not made any compound paths work with Swift, yet they work fine in Objective-C. Dose this have to do with optionals? Values for simple paths are returned wrapped.

1

There are 1 best solutions below

3
On

As soon as you change that last line to

myInstance.valueForKeyPath("linkedInstance.integerProperty")

your Playground will play a lot nicer with you.

The lesson is: Do not confuse valueForKey: with valueForKeyPath:! The expression valueForKey("linkedInstance.integerProperty") can never succeed in Swift or in Objective-C, because"linkedInstance.integerProperty" is not a key - it is a key path.