How do I compare two dictionaries in Swift?

前端 未结 4 1797
暖寄归人
暖寄归人 2020-11-27 04:15

Is there an easy way to compare two [String: AnyObject] dictionaries in swift, since it doesn\'t accept the == operator?

By comparing two

4条回答
  •  臣服心动
    2020-11-27 04:47

    Swift 4 Update:

    Comparing Dictionaries is now native! (Docs here)


    Swift 3:

    Leo Dabus already has an excellently written post with the accepted solution. However, for me, I found that it needed one more step to be fully usable. As you can see from his code, you need to set your dictionary type to [AnyHashable: Any], or otherwise you'll get Binary operator '==' cannot be applied to two '[String : Any]' operands, to use a dictionary common in deserializing JSON for my example.

    Generics to the rescue!:

    // Swift 3.0
    func == (left: [K:V], right: [K:V]) -> Bool {
        return NSDictionary(dictionary: left).isEqual(to: right)
    }
    

    or in another case I had, with [String: Any?]:

    func == (left: [K:V?], right: [K:V?]) -> Bool {
        guard let left = left as? [K: V], let right = right as? [K: V] else { return false }
        return NSDictionary(dictionary: left).isEqual(to: right)
    }
    

提交回复
热议问题