setValueForKeys失败了Swift

我在Playground中有以下代码:

class Pokemon : NSObject { var name :String! var id :Int? var imageURL :String! var latitude :Double! var longitude :Double! init(dictionary :[String:Any]) { super.init() setValuesForKeys(dictionary) } } let dict :[String:Any] = ["name":"John","imageURL":"someimageURL","latitude":45.67] let pokemon = Pokemon(dictionary: dict) 

当调用setValuesForKeys时,它会抛出一个exception,说明如下:

 *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key latitude.' 

我有关键的“纬度”但由于某种原因它无法找到它。 有任何想法吗!

解决方案:阅读所选答案,这是更新后的代码:

 class Pokemon : NSObject { var name :String! var id :Int = 0 var imageURL :String! var latitude :Double = 0 var longitude :Double = 0 init(dictionary :[String:Any]) { super.init() setValuesForKeys(dictionary) } } 

Double!Double! (类似的Double? )在Objective-C世界中没有对应关系,所以它没有作为Objective-C属性公开 ,因此Key-Value Coding找不到名为“latitude”和崩溃的键。

如果需要KVC,您应该将这些字段转换为非可选字段。

 class Pokemon : NSObject { var name: String! var id: Int = 0 var imageURL: String! var latitude: Double = 0.0 var longitude: Double = 0.0 init(dictionary: [String: Any]) { super.init() setValuesForKeys(dictionary) } }