This question already has answers here:
How do I compare two dictionaries in Swift?
                                
                                    (4个答案)
                                
                        
                                5个月前关闭。
            
                    
我有一个用例,我需要比较两个我不知道类型的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
}


这不是完美的,但是可以满足我的需求

10-08 05:45