我是Swift的新手,我遇到错误问题此类不符合键值编码 - 。
我重读了所有相关主题,但没有找到解决此问题的方法。
请查看代码并给我一些建议,我做错了什么?
class FriendScore: NSObject {
var name:String?
var highestScore:Int?
}
var allScoresArr = [FriendScore]()
var dataArr = [[String:Any]]()
dataArr =[["name": "Ben", "highestScore": 15],["name": "Alex", "highestScore": 12]]
for user in dataArray {
if let dictionary = user as? [String:Any] {
let friendScore = FriendScore()
//Error Happens Here "Thread Breakpoint"
friendScore.setValuesForKeys(dictionary)
allScoresArr.append(friendScore)
}
}
print(allScoresArr)
错误:
<__lldb_expr_73.FriendScore 0x608000266080>
setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key highestScore.
'libc++abi.dylib: terminating with uncaught exception of type NSException
答案 0 :(得分:3)
据我所知,你的例子有很多错误。首先,您定义var dataArr
,然后重新定义let dataArr
,然后实际迭代dataArray
。
除此之外,您的dataArr是一个字典数组。每个字典都是[String: Any]
类型。当您致电setValuesForKeys(dictionary)
时,它会尝试将name
和highestScore
的值设置为字典中的值。这些值中的每一个都是Any
类型,但FriendScore
类所期望的是String
类型name
的值,类型Int
的值为highestScore
。您需要将每个值转换为正确的类型:
class FriendScore: NSObject {
var name:String?
var highestScore:Int?
}
let dataArr = [["name": "Ben", "highestScore": 15],["name": "Alex", "highestScore": 12]]
for user in dataArr {
let friendScore = FriendScore()
friendScore.name = user["name"] as? String
friendScore.highestScore = user["highestScore"] as? Int
}
如果您的类有多个相同类型的参数,您只需使用setValuesForKeys
并传递一个除Any
以外的显式类型的字典。