Search code examples
swiftswift3

How to check if two [String: Any] are identical?


Is there any way to check if two [String: Any] are identical ?

let actual: [[String: Any]] = [
    ["id": 12345, "name": "Rahul Katariya"],
    ["id": 12346, "name": "Aar Kay"]
]
var expected: [[String: Any]]!

if actual == expected {
    print("Equal")
}

Basically i want Dictionary to conform to Equatable protocol in Swift 3.


Solution

  • For Xcode 7.3, swift 2.2 A dictionary is of type : [String:AnyObject] or simply put NSDictionary

    let actual: [String: AnyObject] = ["id": 12345, "name": "Rahul Katariya"]
    
    
    var expected: [String: AnyObject] = ["id": 12346, "name": "Aar Kay"]
    
    
    print(NSDictionary(dictionary: actual).isEqualToDictionary(expected))//False
    

    For Xcode 8.beta 6, Swift 3

    Dictionary is defined as:

    struct Dictionary<Key : Hashable, Value> : Collection, ExpressibleByDictionaryLiteral
    

    NSDictionary has the following convenience initializer:

    convenience init(dictionary otherDictionary: [AnyHashable : Any])
    

    So you can use AnyHashable type for Key and Any type for Value

    let actual: [String: Any] = ["id": 12345, "name": "Rahul Katariya"]
    
    var expected: [String: Any] = ["id": 12346, "name": "Aar Kay"]
    
    
    print(NSDictionary(dictionary: actual).isEqual(to: expected))//False