I have simple class User
. When I try to call valueForKey
where key is optional value I get an error. See below:
class User : NSObject{
var name = "Greg"
var isActive:Bool?
}
var user = User()
user.isActive = true // initiated
var ageValue : AnyObject! = user.valueForKey("name")// OK
var isActive : AnyObject! = user.valueForKey("isActive") //ERROR
<__lldb_expr_862.User 0x7fa321d0d590> valueForUndefinedKey:]: this class is not key value coding-compliant for the key isActive.
If I'll initiate the value, it will work:
var isActive:Bool = true
How to make it work with optional values?
I'm not sure exactly why you want to do this and if you really have to use key-value coding, is it for obj-c compatibility?
It might also be something that will be fixed later when Swift is updated. But a (temporary) workaround now could be to override the valueForKey function and take special care of your optionals. Something like this:
override func valueForKey(key: String!) -> AnyObject! {
if key == "isActive" {
if self.isActive == nil {
return NSNumber(bool: false)
}
else {
return NSNumber(bool: self.isActive!)
}
}
return super.valueForKey(key)
}
Keep in mind that I basically never use key-value coding myself so I don't know if it is a bad idea to override that function... Also in obj-c BOOL isn't nillable so I assume you want false in that case? (For Bool types specifically I would rather skip the optional I think)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With