如何在swift中比较两个字典? [英] how do I compare two dictionaries in swift?

查看:1896
本文介绍了如何在swift中比较两个字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



通过比较两个字典,我的意思是检查他们有相同的确切键,并为每个键有相同的值。

解决方案

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

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

println(NSDictionary ).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 8 beta 6•Swift 3



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

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




说明



元素是键值对的集合。 A
字典是一种哈希表,提供对其包含的
条目的快速访问。表中的每个条目使用其
键来标识,该键是诸如字符串或数字的可哈希类型。你使用
键来检索相应的值,它可以是任何对象。在
其他语言中,类似的数据类型称为散列或关联的
数组。通过使用字典字面量创建新字典。 A
字典文字是逗号分隔的键值对列表,在
中,冒号将每个键与其关联值分隔开,用方括号括起
。您可以将字典字面值指定给变量
或常量,或将其传递给需要字典的函数。


如何创建HTTP响应代码及其相关消息的字典:

  var responseMessages = [200:OK,
403:禁止访问,
404:文件未找到,
500:内部服务器错误]




responseMessages变量被推断为类型 [Int:String]
字典的键类型是 Int
字典的值类型是 String

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

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

任何符合Hashable协议的类型都可以用作字典的Key类型,包括所有Swift的基本类型。您可以使用自己的自定义类型作为字典键,使其符合Hashable协议。






以定义自定义运算符:



从文档:

  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:任何] = [key1:100,key2:Date()]

print(dic4 == dic5)//二进制运算符==不能应用于两个`[String:Any] `operands

但我们可以扩展 == 操作符功能使用NSDictionary初始化器:

 方便init(dictionary otherDictionary:[AnyHashable:Any])






  public func ==(lhs: [AnyHashable:Any],rhs:[AnyHashable:Any]) - > Bool {
return NSDictionary(dictionary:lhs).isEqual(to:rhs)
}


$ b b




测试:

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

print(of:dic4),type(of:dic5),type ))//字典< AnyHashable,Any>字典< AnyHashable,Any>字典< AnyHashable,Any>

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


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

by comparing two dictionaries I mean checking that they have the same exact keys and for every key they have the same values.

解决方案

As already mentioned by Hot Licks you can use NSDictionary method isEqualToDictionary() to check if they are equal as follow:

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

you can also implement a custom operator "==" as follow:

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

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


Xcode 8 beta 6 • Swift 3

From the docs, dictionary is now defined as a struct:

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.

Here’s how you would create a dictionary of HTTP response codes and their related messages:

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.

To create a dictionary with no key-value pairs, use an empty dictionary literal ([:]).

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

Any type that conforms to the Hashable protocol can be used as a dictionary’s Key type, including all of Swift’s basic types. You can use your own custom types as dictionary keys by making them conform to the Hashable protocol.


We don't need to define a custom operator anymore:

From the docs:

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


Testing:

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

In the example above all dictionary keys and values are the same type. If we try to compare two dictionaries of type [String: Any] Xcode will complain that Binary operator == cannot be applied to two [String: Any] operands.

    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

But we can extend the == operator functionality using the NSDictionary initializer:

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


public func ==(lhs: [AnyHashable: Any], rhs: [AnyHashable: Any] ) -> Bool {
    return NSDictionary(dictionary: lhs).isEqual(to: rhs)
}


Testing:

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

print(type(of:dic4),type(of:dic5),type(of:dic6)) // Dictionary<AnyHashable, Any> Dictionary<AnyHashable, Any> Dictionary<AnyHashable, Any>

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

这篇关于如何在swift中比较两个字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆