[英]setValueForKeys is failing Swift
I have the following code in the Playground: 我在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)
When the call to setValuesForKeys is made then it throws an exception saying the following: 当调用setValuesForKeys时,它会抛出一个异常,说明以下内容:
*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__lldb_expr_13.Pokemon 0x6000000ffd00> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key latitude.'
I have the key "latitude" but for some reason it is not able to find it. 我有关键的“纬度”但由于某种原因它无法找到它。 Any ideas!
有任何想法吗!
The type Double!
Double!
型Double!
(similarly Double?
) has no correspondence in the Objective-C world, so it is not exposed as an Objective-C property , so Key-Value Coding cannot find a key named "latitude" and crash. (类似
Double?
)在Objective-C世界中没有对应关系,因此它不会作为Objective-C属性公开 ,因此Key-Value Coding无法找到名为“latitude”和崩溃的键。
You should convert those fields to non-optional if you need KVC. 如果需要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)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.