gpt4 book ai didi

swift - 如何检查两个 [String : Any] are identical?

转载 作者:搜寻专家 更新时间:2023-10-30 21:49:23 24 4
gpt4 key购买 nike

有什么方法可以检查两个 [String: Any] 是否相同?

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

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

基本上我希望 Dictionary 符合 Swift 3 中的 Equatable 协议(protocol)。

最佳答案

对于 Xcode 7.3,swift 2.2字典的类型是:[String:AnyObject] 或者简单地把 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

适用于Xcode 8.beta 6、Swift 3

字典定义为:

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

NSDictionary 有以下便利的初始值设定项:

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

因此您可以对 Key 使用 AnyHashable 类型,对 Value 使用 Any 类型

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

关于swift - 如何检查两个 [String : Any] are identical?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39164964/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com