OC中有个可变字典和不可变字典。swift中就是let
和var
来区分可变和不可变的。
新增
var dic = ["name":"000","age":18] as [String : Any]
dic["title"] = "uuu"
print(dic)
修改
var dic = ["name":"000","age":18] as [String : Any]
// dic["title"] = "uuu"
dic["name"] = "007"
print(dic)
如果key存在就是修改,不存在就是新增。
删除
var dic = ["name":"000","age":18] as [String : Any]
dic.removeValue(forKey:"age")
print(dic)
字典是通过key来定位值的,key必须是可以’hash 哈希‘ hash就是将字符串变成唯一的'整数',便于查找,提高字典遍历的速度
遍历
var dic = ["name":"000","age":18,"title":"888"] as [String : Any]
for e in dic {
print(e)
print("\(e.key) \(e.value)")
}
打印出的结果如下:
(key: "name", value: "000")
name 000
(key: "age", value: 18)
age 18
(key: "title", value: "888")
title 888
//前面的是key,后面的是value,具体的名字可以随便。
for (key,value) in dic {
print("\(key) \(value)")
}
合并
var dic = ["name":"000","age":18,"title":"888"] as [String : Any]
let dic1 = ["name":"da","hegiht":190] as [String : Any]
for e in dic1 {
dic[e.key] = dic1[e.key]
}
//如果key存在会修改,key不存在会新增
print(dic)
总结
相比OC来说,swift简单一些