1、定义字典
func demo() {
//1、定义一个字典
//[KEY: VALUE] = ["name" : "张", "age" : 18]
let dict: [String : Any] = ["name" : "Raven", "age" : 25]
print(dict)
//输出结果:["name": "Raven", "age": 25]
//2、定义一个数组,元素为字典
let array = [
["name" : "z", "age" : 12],
["name" : "w", "age" : 13]
]
print(array)
//输出结果:[["name": "z", "age": 12], ["name": "w", "age": 13]]
}
2、增、删、改
func demo1() {
var dict:[String:Any] = ["name" : "zhang", "age" : 19]
//1、增
dict["title"] = "大哥"
print(dict)
//输出结果:["name": "zhang", "age": 19, "title": "大哥"]
//2、修改
dict["name"] = "wang"
print(dict)
//输出结果:["name": "wang", "age": 19, "title": "大哥"]
//3、删除
//字典是通过 KEY 来定位值的, KEY 必须是可以 ‘hash哈希’MD5就是一种
//hash 就是将字符串变成唯一的 ‘整数’, 便于查找,提高字典遍历的速度
dict.removeValue(forKey: "age")
print(dict)
//输出结果:["name": "wang", "title": "大哥"]
}
3、遍历
func demo2() {
let dict:[String:Any] = ["name" : "zhang", "age" : 19]
for e in dict {
print("\(e.key)-\(e.value)")
// 输出结果:
// name-zhang
// age-19
}
}
4、合并
func demo3() {
var dict:[String:Any] = ["name" : "Raven", "age" : 20, "title" : "老板"]
let dict1:[String:Any] = ["name" : "小明", "height" : 190]
for e in dict1 {
dict[e.key] = dict1[e.key]
}
print(dict)
//输出结果:["name": "小明", "age": 20, "title": "老板", "height": 190]
}
网友评论