Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

valueForKey throws error for optional value, Swift

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?

like image 1000
snaggs Avatar asked Oct 31 '22 18:10

snaggs


1 Answers

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)

like image 123
osanoj Avatar answered Dec 04 '22 16:12

osanoj