学习笔记
1、字典初始化
var dict = [:] //初始化无类型空字典
dict = ["1":"aaa","2":"bbb"]
print(dict)
dict = [1:"1","2":2] //key 和value都是不定类型的
print(dict)
let dict2:Dictionary<String,Int> = ["1":111,"2":222] //限定键值类型
print(dict2)
let dict3:[String:Int] = ["1":111]
print(dict3)
2、字典操作
var dict4 = ["apple":"苹果","bag":"包"]
print(dict4["apple"])
dict4["apple"] = "橘子" //修改值
print(dict4)
dict4.updateValue("苹果",forKey: "apple") //更新键值 如果key存在 更新键值对并且返回key之前的对应的value
print(dict4.updateValue("苹果",forKey: "apples")) //如果key 不存在将增加新的键值对并返回nil
if let origin = dict4.updateValue("aaaaa",forKey: "appl") {
print("origin \(origin)")
}
print(dict4)
if let origin = dict4.removeValueForKey("apple") {
} else {
//不存在key 返回nil 字典不变
if let origin = dict4.removeValueForKey("aaaaa") {
print(origin)
print(dict4.removeValueForKey("aaaaa")) //如果key不存在 不作操作并返回nil
}
print(dict4)
3、字典遍历
for (key,value) in dict4 { //使用元组 遍历键值对
print("\(key) : \(value)")
for key in dict4.keys { //遍历所有key
print(key)
for value in dict4.values { //遍历所有value
print(value)
}