swift3.0 字典的基本用法

时间:2023-01-31 18:41:48

自学swift3.0,如果有什么错误或建议的话欢迎吐槽哦~

        //1.字典的定义使用[key:value,key:value]快速定义
let dic:[String:Any] = ["name":"张三","age":22]
print(dic)

//数组字典
let arrDic:[[String:Any]] = [
["name":"张三","age":22],
["name":"李四","age":24]
]
print(arrDic)
//2.可变字典的增删改查
var dictionary:[String:Any] = ["name":"张三","age":22]
print(dictionary)

/*
key存在则为修改,key不存在 则为添加
*/
//增加键值对
dictionary["score"] = 99
print(dictionary)

//修改键值对
dictionary["age"] = 33
print(dictionary)

//删除键值对
// ps: 字典是通过KEY来定位值的,所有的KEY必须是可以 hash/哈希 的 (md5就是一种哈希,哈希就是将字符串变成唯一的整数,便于查找,能够提高字典遍历的速度)
// dictionary.removeValue(forKey: <#T##Hashable#>)

dictionary.removeValue(forKey: "score")
print(dictionary)

//字典遍历
//写法一
for e in dictionary {
print("key = \(e.key) value = \(e.value)")

}

//写法二
for (key,value) in dictionary {
print("key = \(key) value = \(value)")
}

//字典合并
var dic1 = ["name":"小明","score":"88"]
print(dic1)
let dic2 = ["teacher":"老大"]

for (key,value) in dic2 {
dic1[key] = value
}
print(dic1)