Swift集合(Dictionary)

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)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容