可变性
不可变还意味着你不能改变字典里某个键的值。一个不可变的字典一旦被设置值后,它里面的内容就不能再改变。
构造Dictionary
//空Dictionary
var namesOfIntegers = Dictionary<Int, String>()
//带初始值
var dic: Dictionary<String, String> = ["name": "张三", "sex": "男"]
//让编译器判断类型的
var dict2 = ["name": "张三", "sex": "男"]
增
dict["age"] = "18"
删
dict["name"] = nil //删除某个元素
let removedValue = dict.removeValueForKey("name") //返回删除的value,key不存在返回nil
改
dict["name"] = "李四" //name存在的话就修改,不存在就是增加
//updateValue方法,存在就修改,不存在增加,并返回旧值(不存在旧值返回nil)
if let oldValue = dict.updateValue("20", forKey: "age") {
print("The old value for DUB was \(oldValue).")
}
查
//dict.count返回元素数
print("The dictionary have \(dict2.count) items.")
//用key查value
if let name = dict["name"] {
print("The name is \(name) .")
} else {
print("That name is not in the dictionary.")
}
//遍历访问
for (key, value) in dict {
print("\(key): \(value)")
}
for key in dict.keys {
print("key : \(key)")
}
for value in dict.values {
print("value : \(value)")
}
转数组
//keys数组
let keys = Array(dict.keys)
//values数组
let values = Array(dict.values)
网友评论