一、字典的定义
//可变字典,用泛型定义字典类型,当然类型定义可以省略
var dic11:Dictionary<Int,Int> = [0:1,1:2]
dic11[1] = 3 //修改字典内容
dic11 //[0: 1, 1: 3]
//不可变字典
let dic12:[String:Any] = ["a":4,"b":5,"c":6,"d":"1"]
二、字典元素的基本操作
- 任意值类型通常用 Any,而不是 NSObject
var dic21:[AnyHashable:Any] = [1:1,2:2,"a":"a","b":"b"]
- 增加元素
dic21["c"] = 3
dic21 //["b": "b", "a": "a", 2: 2, 1: 1, "c": 3]
dic21["a"] = 1
dic21 //["b": "b", "a": 1, 2: 2, 1: 1, "c": 3]
通过这种方式,如果字典中存在某个 键-值,就进行修改,如果不存在就进行添加此 键-值
- 删除元素
dic21.removeValue(forKey: "a")
或
let index = dic21.index(forKey: "a")
dic21.remove(at: index!)
结果为:
dic21 //["b": "b", 2: 2, 1: 1, "c": 3]
- 改元素
dic21[2] = "b"
dic21 //["b": "b", 2: "b", 1: 1, "c": 3]
dic21.updateValue("a", forKey: 1)
dic21 //["b": "b", 2: "b", 1: "a", "c": 3]
- 查元素
dic21[1] //"a"
三、 字典的基本操作
var dic31:[AnyHashable:Any] = [1:1,2:2,"a":"A","b":"B"]
- 字典的遍历
- 遍历所有键
for key in dic31.keys {
print(key)
}
- 遍历所有值
for value in dic31.values {
print(value)
}
- 遍历所有键值
for (key,value) in dic31 {
print(key,value)
}
- 字典的合并,通过遍历完成
var dic32:[AnyHashable:Any] = [1:2,2:3,"aa":"a","bb":"b"]
//将字典 dic31 和 dic32 合并,若有相同键,则保留 dic32 中的键值
for key in dic32.keys{
dic31[key] = dic32[key]
}
dic31 //["b": "B", "a": "A", 2: 3, "aa": "a", 1: 2, "bb": "b"]
四、补充:扩展
extension Dictionary{
static func + (dic1:inout Dictionary,dic2:inout Dictionary) -> Dictionary {
for key in dic2.keys {
dic1[key] = dic2[key]
}
return dic1
}
}
var d4 = [1:1,2:"a"] as [Int : Any]
var d5:[Int : Any] = [3:1,4:2]
d4 + d5 //[2: "a", 3: 1, 1: 1, 4: 2]
两个相加的字典 键值 类型必须要一致才可以。