swift - 我如何在 Swift 中比较两个字典?

标签 swift dictionary compare

有没有一种简单的方法可以在 swift 中比较两个 [String: AnyObject] 字典,因为它不接受 == 运算符?

通过比较两个字典,我的意思是检查它们是否具有完全相同的键,并且对于每个键它们是否具有相同的值。

最佳答案

正如 Hot Licks 已经提到的,您可以使用 NSDictionary 方法 isEqualToDictionary () 检查它们是否相等,如下所示:

let dic1: [String: AnyObject] = ["key1": 100, "key2": 200]
let dic2: [String: AnyObject] = ["key1": 100, "key2": 200]
let dic3: [String: AnyObject] = ["key1": 100, "key2": 250]

println( NSDictionary(dictionary: dic1).isEqualToDictionary(dic2) )   // true
println( NSDictionary(dictionary: dic1).isEqualToDictionary(dic3) )  // false

您还可以实现自定义运算符“==”,如下所示:

public func ==(lhs: [String: AnyObject], rhs: [String: AnyObject] ) -> Bool {
    return NSDictionary(dictionary: lhs).isEqualToDictionary(rhs)
}

println(dic1 == dic2)   // true
println(dic1 == dic3)   // false

Xcode 9 • Swift 4

从文档中,字典现在被定义为一个结构:

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

Description

A collection whose elements are key-value pairs. A dictionary is a type of hash table, providing fast access to the entries it contains. Each entry in the table is identified using its key, which is a hashable type such as a string or number. You use that key to retrieve the corresponding value, which can be any object. In other languages, similar data types are known as hashes or associated arrays. Create a new dictionary by using a dictionary literal. A dictionary literal is a comma-separated list of key-value pairs, in which a colon separates each key from its associated value, surrounded by square brackets. You can assign a dictionary literal to a variable or constant or pass it to a function that expects a dictionary.

以下是创建 HTTP 响应代码及其相关消息的字典的方法:

var responseMessages = [200: "OK",
                        403: "Access forbidden",
                        404: "File not found",
                        500: "Internal server error"]

The responseMessages variable is inferred to have type [Int: String]. The Key type of the dictionary is Int, and the Value type of the dictionary is String.

要创建没有键值对的字典,请使用空字典文字 ([:])。

var emptyDict: [String: String] = [:]

任何符合 Hashable 协议(protocol)的类型都可以作为字典的 Key 类型,包括 Swift 的所有基本类型。您可以使用自己的自定义类型作为字典键,方法是使它们符合 Hashable 协议(protocol)。


我们不再需要定义自定义运算符:

来自文档:

static func ==(lhs: [Key : Value], rhs: [Key : Value]) -> Bool

测试:

let dic1 = ["key1": 100, "key2": 200]
let dic2 = ["key1": 100, "key2": 200]
let dic3 = ["key1": 100, "key2": 250]

print(dic1 == dic2)   // true
print(dic1 == dic3)   // false

在上面的示例中,所有字典键和值都是相同的类型。 如果我们尝试比较 [String: Any] 类型的两个字典,Xcode 会提示二元运算符 == 不能应用于两个 [String: Any] 操作数。

let dic4: [String: Any] = ["key1": 100, "key2": "200"]
let dic5: [String: Any] = ["key1": 100, "key2": "200"]
let dic6: [String: Any] = ["key1": 100, "key2": Date()]

print(dic4 == dic5)  // Binary operator == cannot be applied to two `[String: Any]` operands

但是我们可以扩展 == 运算符功能来实现中缀运算符,将 Swift Dictionary 转换为 NSDictionary 并将字典值限制为 Hashable Protocol:


Xcode 11 • Swift 5.1

public func ==<K, L: Hashable, R: Hashable>(lhs: [K: L], rhs: [K: R] ) -> Bool {
   (lhs as NSDictionary).isEqual(to: rhs)
}

测试:

let dic4: [String: AnyHashable] = ["key1": 100, "key2": "200"]
let dic5: [String: AnyHashable] = ["key1": 100, "key2": "200"]
let dic6: [String: AnyHashable] = ["key1": 100, "key2": Date()]

print(dic4 == dic5)   // true
print(dic4 == dic6)   // false

let dic7: [String: String] = [ "key2": "200"]
let dic8: [String: Date] = [ "key2": Date()]
print(dic7 == dic8)   // false

关于swift - 我如何在 Swift 中比较两个字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44926988/

相关文章:

Swift:String.join() 如何工作自定义类型?

通过变量快速访问结构

python - 将列表转换为嵌套字典

powershell - 如何重新组织 powershell 的比较对象输出?

ios - 如何在 iOS 应用程序中使用 'Service account' 实现 Vision API?

swift - 如何在 Swift 中通过实际类型限制 switch case

c++ - std::map 超出需要的比较

javascript - 使用 Django,将 Python 字典发送到 HTML 页面并将其转换为 Javascript 脚本中的 Javascript 数组

java - 比较两个 ArrayLists - 一个作为另一个的子集

Java 如何比较 XML 数据与文件扩展名