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.
As soon as you change that last line to
your Playground will play a lot nicer with you.
The lesson is: Do not confuse
valueForKey:
withvalueForKeyPath:
! The expressionvalueForKey("linkedInstance.integerProperty")
can never succeed in Swift or in Objective-C, because"linkedInstance.integerProperty"
is not a key - it is a key path.