初始化
swift中需要指出字典中的类型
//初始化字典
var mdict:[String:Any] = [:]
var mdict1 = [String:Any]()
let dict:[String:Any] = ["name":"lhr","age":"100"]
增加
//添加元素
mdict["a"] = "第一个值"
mdict["c"] = "第三个值"
删
//删除全部
mdict.removeAll()
//删除key为a的 键值对
mdict.removeValue(forKey: "a")
改
//修改元素
mdict.updateValue("第二个增加的值", forKey: "b")
mdict["a"] = "重新赋值"
其他属性
//盘点字典是否为空
print(dict.isEmpty)
//获取字典的建支个数
print(dict.count)
//获取字典所有的key 和balues
print(dict.keys,dict.values)
print(dict["name"])
遍历字典 合并字典
//遍历字典
for objc in dict {
print("字典的key是:\(objc.key) 字典的values是:\(objc.value)")
}
var dict1:[String:Any] = ["姓名":"张三","昵称":"法外狂徒","age":"20"]
let dict2:[String:Any] = ["do":"抢钱","性别":"不男不女"]
for (key,value) in dict2 {
dict1[key] = value
}
print(dict1)