创建一个不可变字典
let dic:[String : Any] = ["name":"lxd", "age":26, "height":1.88]
或者
let dict2 = ["name" : "lxd", "age" : 18, "height" : 1.68] as [String : Any]
创建一个可变字典
var dictM = [String : Any]()
添加元素
dictMc["name"] = "lxd"
dictMc["age"] = 25
删除元素
dictM.removeValue(forKey: "age")
修改元素
dictM["name"] = "lxdxx"
或者
dictM.updateValue("boy", forKey: "name")
通过key取出value
let name = dictM["name"]
遍历字典
// 遍历字典中所有的key
for key in dictM.keys {
print(key)
}
// 遍历字典中所有的value
for value in dictM.values {
print(value)
}
// 遍历字典中所有的key/value
for (key, value) in dictM {
print(key, value)
}
合并字典
var dict1 = ["name" : "lxd", "age" : 18] as [String : Any]
let dict2 = ["weight" : 70, "phoneNum" : "15314288888"] as [String : Any]
for (key, value) in dict2 {
dict1[key] = value
}
网友评论