import UIKit
//1定义字典
//1.1定义不可变字典,系统会自动判断[]里面存放的是键值对还是数组元素
let dic1 = ["name":"zhengyanfeng" , "age":16 , "height":1.88] as [String : Any]
//1.2定义可变字典
var dic2 = [String : Any]()
//2.1可变字典添加元素
dic2["name"] = "zhengyanfeng"
dic2["age"] = 18
dic2["height"] = 1.88
dic2["weight"] = 125
//2.2删除元素
dic2.removeValue(forKey: "name")
//2.3修改元素
dic2["age"] = 16
//2.4获取字典中的某一个元素
dic2["age"]
//3遍历字典
//3.1遍历字典中所有的key
for key in dic2.keys {
print(key)
}
//3.2遍历字典中所有的值
for value in dic2.values {
print(value)
}
//3.3遍历字典中所有的键值对
for (key , value) in dic2 {
print(key)
print(value)
}
//3.4合并字典
//即使字典类型一致,也不能相加合并
var dic3 = ["name":"zhengyanfeng"]
let dic4 = ["school":"qinghua"]
for (key , value) in dic4 {
dic3[key] = value
}
dic3
swit 字典用法,增删改查、合并
最新推荐文章于 2024-01-31 16:21:31 发布