字典
swift 字典不仅可以存储对象类型的值,还可以存储基本数据类型的值,结构体,枚举值。字典本质上也是结构体。
- 字典声明
let dic1 = ["key1":1, "key2":2, "key3":3, "key4":4]
let dic2 = String:Int
let dic3:[String:Int] = ["key1":1, "key2":2, "key3":3, "key4":4]
let dic4:Dictionary = ["key1":1,"key2":2];
// 字典范性定义的方式
let dic5:Dictionary<String, Int> = ["key1":1, "key2":2, "key3":3]
let dic6:[String:AnyObject] = ["key1":1 as AnyObject, "key2":2 as AnyObject, "key3":"value3" as AnyObject, "key4":4 as AnyObject]
let dic7:NSDictionary = NSDictionary(dictionary: ["key1":1, "key2":2, "key3":3, "key4":4])
//使用init()构造器
let dic8:[String:String] = Dictionary<String,String>()
//使用init(minimumCapacity:Int) 并且指定了字典的最小容量
let dic9:[String: Int] = Dictionary<String, Int>(minimumCapacity: 5) - 字典中元素的个数
print(dic3.count)
print(dic2.count) - 字典是否为空
print(dic1.isEmpty) - 获取字典中的key/value
print(dic7.allKeys)
print(dic7.allValues)
print(dic4["key1"]!)
print(dic5["key2"]!) - 修改字典
var dic10:Dictionary<String,String>
dic10 = ["key1":"value1","key2":"value2"]
dic10["key1"] = "changeString"
print(dic10) - 添加字典
var dic10:Dictionary<String,String>
dic10 = ["key1":"value1","key2":"value2"]
dic10["key3"] = "value3"
dic10.updateValue("value", forKey: "key4") - 删除
var dic10:Dictionary<String,String>
dic10 = ["key1":"value1","key2":"value2"]
// 删除指定key
dic10["key1"] = nil
dic10.removeValue(forKey: "key2")
// 删除全部
dic10 = [:]
dic10.removeAll()
// 对于 keepCapacity :false /true ,根据需求选择 即可;区别是true的话,会保持数据容量,占据空间?
dic10.removeAll(keepingCapacity: true)
遍历字典
for (key, value) in dic3 {
print(key,value)
}
for key in dic3.keys {
print(key)
}
for value in dic3.values {
print(value)
}