1、字典的概念
- 字典储存无序的互相关联的同一类型的键和同一类型的值的集合
- 字典类型的全写方式 Dictionary<Key, Value>,简写方式 [Key: Value],建议使用简写方式
- 字典的 key 必须是可哈希的
2、创建空字典
- 初始器方式
- 简写方式
- 字面量方式
//初始化器
let dict1 = Dictionary<String, Int>()
//简写方式
let dict2 = [String: Int]()
//字面量
let dict3: Dictionary<String, Int> = [:]
let dict4 = ["zhangsan": 18, "lisi": 24, "wangwu": 34]
3、count 和 isEmpty
- 可以使用 count 只读属性来找出 Dictionary 拥有多少元素
- 使用布尔量 isEmpty 属性检查字典是否为空
let dict4 = ["zhangsan": 18, "lisi": 24, "wangwu": 34]
print(dict4.count)
print(dict4.isEmpty)
4、遍历字典
- For-In 循环
- 可以通过访问字典的 keys 和 values 属性来取回可遍历的字典的键或值的集合
- Swift 的 Dictionary 类型是无序的。要以特定的顺序遍历字典的键或值,使用键或值的 sorted() 方法
let dict = ["zhangsan": 18, "lisi": 24, "wangwu": 34]
for (keys, values) in dict {
print("keys : \(keys), values : \(values)")
}
for key in dict.keys.sorted() {
print("key : \(key), value : \(dict[key])")
}
5、字典常用操作
1> 添加或更新元素
- 使用下标添加或更新元素
- 使用 updateValue(_:forKey:) 方法添加或更新元素,返回一个字典值类型的可选项值
var dict = ["zhangsan": 18, "lisi": 24]
dict.updateValue(25, forKey: "wangwu")
print(dict.prefix(upTo: dict.startIndex)) //获取字典切片
print(dict)
2> 移除元素
- 使用下标脚本语法给一个键赋值 nil 来从字典当中移除一个键值对
- 使用 removeValue(forKey:)来从字典里移除键值对。这个方法移除键值对如果他们存在的 话,并且返回移除的值,如果值不存在则返回 nil
var dict = ["zhangsan": 18, "lisi": 24, "wangwu": 25]
//dict.remove(at: dict.startIndex)
//dict.removeValue(forKey: "lisi")
//dict.removeAll()
dict.removeAll(keepingCapacity: true)
print(dict.capacity)
print(dict)
3> 合并两个字典
- merge(_:uniquingKeysWith:)
var dict = ["a": 1, "b": 2]
let dict2 = dict.merging(["a": 3, "c": 4]) { (current, _) -> Int in current }
print(dict2)
let dict3 = dict.merging(["a": 5, "d": 6]) { (_, new) -> Int in
new
}
print(dict3)
4> firstIndex
- 虽然字典是无序的,但是每个kv对在扩容之前的位置是稳定的。如果你需要保持顺序的kv对 可以使用 KeyValuePairs
let dict: KeyValuePairs = [
"Math": 89,
"Chinese": 87,
"English": 78
]
print(dict.first!)
print(dict) //完全按书写的顺序输出
5> 字典另外一些常用操作
let dict = [
"Math": 89,
"Chinese": 87,
"English": 78
]
print(dict.contains(where: { $0.value == 89}))
print(dict.allSatisfy({ $0.key == "Math"}))
print(dict.contains(where: { (dict) -> Bool in
dict.key == "Math"
}))
print(dict.min(by: { (dict1, dict2) -> Bool in
dict1.value < dict2.value
}))
print(dict.max(by: { $0.value < $1.value }))