Swift - setValuesForKeys(dictionary) 错误 - 此类不符合键的键值编码

Rur*_*rom 1 arrays dictionary swift

我是 Swift 新手,我有一个错误问题,这个类与 key 的键值编码不兼容

我重新阅读了所有相关主题,但没有找到解决此问题的方法。

请检查代码并给我一些建议,我做错了什么?

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)
Run Code Online (Sandbox Code Playgroud)

错误:

<__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
Run Code Online (Sandbox Code Playgroud)

dro*_*ang 5

据我所知,你的例子有很多错误。首先,定义var dataArr,然后重新定义let dataArr,然后实际迭代dataArray

除此之外,您的 dataArr 是一个字典数组。每个字典都是类型[String: Any]。当您调用 时,它会尝试将和 的setValuesForKeys(dictionary)值设置为字典中的值。这些值中的每一个都是 类型的,但是该类期望的是for类型的值和for类型的值。您需要将每个值转换为正确的类型:namehighestScoreAnyFriendScoreStringnameInthighestScore

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
}
Run Code Online (Sandbox Code Playgroud)

如果您的类具有多个相同类型的参数,您可以简单地使用setValuesForKeys并传递具有除 之外的显式类型的字典Any