Key-value coding in Swift

Key-value coding, long a staple of the Cocoa API, is accessible in Swift, with some caveats.

KVC in Swift requires NSObject

First and foremost, classes on which you intend to use KVC must descend from NSObject. It doesn’t work on base classes. So, this won’t compile:

1
2
3
4
5
6
7
8
9
10
class Boo {
var bar:Bool

init() {
bar = 0
}
}

var b:Boo = Boo()
b.setValue(true, forKey:“bar”) // this line won’t compile

but if we make Boo a subclass of NSObject, everything works as expected.

Optionals don’t work

Perhaps there’s a way of making this work; but I haven’t found it. Consider this class:

1
2
3
4
5
6
class Foo:NSObject {
var bar:Int = 0
var status:Bool = false
var name:String = “”
var boo:Int = 1
}

then we can use KVC:

1
2
f.setValue(42, forKey: “boo”)
let v:Int = f.valueForKey(“boo”) as Int

but if we change the variable boo to an optional:

1
var boo:Int? = 1

then we cannot use KVC.