Dictionary
字典儲存無序的相關(guān)聯(lián)的同一類型的鍵和同一類型的值
字典的key必須是可哈希的
字典的初始化方式
var dict1 = Dictionary<String,Int>()
var dict2 = [String : Int]()
var dict3 : Dictionary<String,Int> = [:]
//字面量創(chuàng)建字典
let dict = ["wang":20,"lisi":30,"zhangsan":32]
//可以用Count的只讀屬性找出dictionary擁有多少元素
//使用isEmpty判斷dictionary是否為空
字典遍歷
//forin循環(huán)
//可以通過訪問字典法的keys和values屬性來取可遍歷的字典的鍵和值的集合
//swift的字典是無序的。要以特定的順序遍歷字典的鍵或者值,可以使用鍵或者值的Sorted()方法
let dic = ["zhangsan":30,"lisi":20,"wangwu":23,"anday":30]
for (key,value) in dic {
print("\(key)=\(value)")
}
//也可以使用enumerate()方法來進(jìn)行字典遍歷,返回的是字典的索引及 (key, value) 對
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
for (key, value) in someDict.enumerated() {
print("字典 key \(key) - 字典 (key, value) 對 \(value)")
}
字典修改
//可以使用 updateValue(forKey:) 增加或更新字典的內(nèi)容。如果 key 不存在,則添加值,如果存在則修改 key 對應(yīng)的值。updateValue(_:forKey:)方法返回Optional值
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
var oldVal = someDict.updateValue("One 新的值", forKey: 1)
//也可以通過指定的 key 來修改字典的值
someDict[1] = "One 新的值"
合并兩個字典
//合并兩個字典
var dictionary = ["a":1,"b":2]
var dictionary2 = ["a":3,"c":3]
//如果重復(fù)key,以前者為主合并
dictionary.merge(dictionary2) { (a, b) -> Int in
a
}
print(dictionary)
//如果重復(fù)key,以后者為主合并
dictionary.merge(dictionary2) { (_, new) -> Int in
new
}
print(dictionary)
字典移除Key-Value
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
//可以使用 removeValueForKey() 方法來移除字典 key-value 對。如果 key 存在該方法返回移除的值,如果不存在返回 nil
var removedValue = someDict.removeValue(forKey: 2)
//也可以通過指定鍵的值為 nil 來移除 key-value(鍵-值)對
someDict[2] = nil
字典轉(zhuǎn)換為數(shù)組
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
let dictKeys = [Int](someDict.keys)
let dictValues = [String](someDict.values)