swift - 如何在swift3中将字典插入到Set中?

标签 swift dictionary set nsdictionary

我有简单的字典,其定义如下:

let dic = ["key" : "value"]

我想将“dic”添加到此 map 中:

var map = Set<NSDictionary>()
//    var map = Set<Dictionary<String,String>>()

_ = map.insert(dic as NSDictionary)

我不想使用“dic as NSDictionary”。

但我不知道如何执行此操作,我在互联网上搜索了很多,但没有任何帮助。

最佳答案

无论填充一组字典的目的是什么,请注意,声明的 dic 类型不是 NSDictionary,而是字符串键和字符串值的 -Swift- 字典 ([String : String])。

因此,您可以将集合声明为:

let dic = ["key" : "value"]
var map = Set<Dictionary<String, String>>()

_ = map.insert(dic as NSDictionary)

但是这里有一个问题!你会得到:

Type 'Dictionary' does not conform to protocol 'Hashable'

那这意味着什么?以及如何解决?

集合是 Swift 中的一种特殊集合,因为它不能有重复的元素,这会导致问“如何确定字典是唯一的”。

作为解决方法,您可以实现类似于以下内容的扩展:

extension Dictionary: Hashable  {
    public var hashValue: Int {
        return self.keys.map { $0.hashValue }.reduce(0, +)
    }

    public static func ==(lhs: Dictionary<Key, Value>, rhs: Dictionary<Key, Value>) -> Bool {
        return lhs.keys == rhs.keys
    }
}

因此您可以执行以下操作:

let dic1 = ["key" : "value"]
let dic2 = ["key2" : "value"]
let dic3 = ["key3" : "value"]
let dic4 = ["key2" : "value"]
let dic5 = ["key3" : "value"]

var map = Set<Dictionary<String, String>>()

_ = map.insert(dic1)
_ = map.insert(dic2)
_ = map.insert(dic3)
_ = map.insert(dic4)
_ = map.insert(dic5)

print(map) // [["key2": "value"], ["key": "value"], ["key3": "value"]] (unordered)

请注意,基于上面实现的扩展,您还可以声明一组 ints 键和 ints 值的字典 - 例如 -:

var intsMap = Set<Dictionary<Int, Int>>()

var d1 = [1: 12]
var d2 = [2: 101]
var d3 = [1: 1000]

intsMap.insert(d1)
intsMap.insert(d2)
intsMap.insert(d3)

print(intsMap) // [[2: 101], [1: 12]] (unordered)

关于swift - 如何在swift3中将字典插入到Set中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49715840/

相关文章:

java - 每次重新创建 Activity 时 SharedPreference Set<String> 都会重置

ios - 动画时将 UIImageView 置于最前面

ios - 对 NSMutableDictionary 进行排序

java - 获取列表的 Powerset 的最佳方法(递归)

android - osmdroid XYTileSource 不显示来自 Android 服务器的图 block

java - For 循环映射覆盖以前的值

c++ - 添加到 C++ 中的集合

swift - 如何创建运算符以实现错误链接?

json - 使用 JSONEncoder 编码/解码符合协议(protocol)的类型数组

ios - 需要替换 SCNLight 属性导致目标从 iOS 10 更改为 9