ValueForKey throws an error for an optional value, Swift

I have a simple User class. When I try to call valueForKey , where the key is an 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 a key value that is compatible with the encoding for the isActive key.

If I start using the value, it will work:

 var isActive:Bool = true 

How to make it work with optional values?

+5
source share
1 answer

I'm not sure why exactly you want to do this, and if you really need to use key encoding, is it for obj-c compatibility?

It could be something that will be fixed later when Swift is updated. But now a (temporary) workaround might be to override the valueForKey function and take special care of your options. Something like that:

 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 never ever use key value encoding, so I donโ€™t know if it is a bad idea to override this function ... Also in obj-c BOOL is not nillable, so I assume you want false in this case ? (For Bool types, I would probably rather skip the optional option)

+2
source

Source: https://habr.com/ru/post/1201142/


All Articles