Swift 字典 Dictionary 集合型別
Dictionary 字典集合型別,類似于 Java 的 map,特點:鍵唯一,值可重復
1. 創建字典
// 創建空字典
var emptyDict1: [Int : String] = [:]
var emptyDict2: Dictionary<Int, String> = Dictionary()
// 指定鍵值型別
var dict: [Int : String] = [0: "Zero", 1: "One", 2: "Two"]
var dict2: Dictionary<Int, String> = Dictionary(dictionaryLiteral: (1, "One"), (2, "Two"))
// 自動推斷鍵值型別
var dictAuto = [0: "Zero", 1: "One", 2: "Two"]
2. 獲取元素
// 獲取元素個數
dict.count // 3
// 判斷字典為空
dict.isEmpty // false
// 獲取鍵對應的值
dict[1] // One
3. 更新鍵值對
// 修改鍵對應的值
dict[0] = "000" // 000
// 如果鍵存在,就更新,否則就新增鍵值對
dict[-1] = "-1" // -1
// 更新鍵對應的值,如果鍵不存在,回傳 nil
if let lastValue = dict.updateValue("new one", forKey: 1) {
print("the last value is \(lastValue)") // the last value is One
}
// 移除鍵值對
dict.removeValue(forKey: -1) // -1
// 移除所有鍵值對
//dict.removeAll()
4. 遍歷字典
// dict [1: "new one", 2: "Two", 0: "000"]
// 遍歷字典的鍵
for ele in dict.keys {
print(ele)
}
// 遍歷字典的值
for ele in dict.values {
print(ele)
}
// 元組遍歷,直接獲取鍵值對
for (key, val) in dict {
print("\(key):\(val)")
}
// 對 key 進行從小到大排序后遍歷,并對值進行拆包
for ele in dict.keys.sorted(by: <) {
print(dict[ele]!)
}
GitHub 原始碼:DictionaryType.playground
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/351017.html
標籤:其他
