>我有一个用例,我需要比较两个我不知道类型的Any
值。
// assuming I have something like:
var myDict = [
"a": "one",
"b": 2,
"c": false
]
var newDict = [
"a": "one",
"c": true
]
func updateDict() -> Bool {
var hasChanged = false
newDict.forEach { (key: String, value: Any) in
if myDict[key] != value {
hasChanged = true
}
myDict[ket] = value
}
return hasChanged
}
既然if myDict[key] != value
不起作用,我该如何实现这一目标?
现在我所做的是:
if let oldValue = values[key] {
changed = (String(describing: oldValue) != String(describing: value))
} else {
changed = true
}
它并不完美,但可以满足我的需要
您可以使用在NSDictionary
上定义的isEqual(to:)
:
var myDict: [String : Any] = [
"a": "one",
"b": 2,
"c": false
]
var newDict: [String : Any] = [
"a": "one",
"c": true
]
NSDictionary(dictionary: myDict).isEqual(to: newDict) // false