Swift 字典 (Dictionaries)

字典是一種用來儲存多個相同型別數值的容器。每個數值 (Value) 都關聯著一個唯一的鍵 (Key)。與陣列不同,字典裡的元素是沒有順序的。

你可以把它想像成現實生活中的字典:你透過查詢一個「單字」(Key) 來找到它的「解釋」(Value)。

建立字典

鍵和值的型別必須明確。例如 [String: Int] 代表這是一個「鍵為字串,值為整數」的字典。

var airports: [String: String] = ["TPE": "Taipei Taoyuan", "NRT": "Tokyo Narita"]

// Swift 自動推斷型別
var codeNames = ["TPE": "Taipei Taoyuan"]

建立空字典:

var namesOfIntegers: [Int: String] = [:]
// 或
var emptyDict = [Int: String]()

存取與修改字典

取得元素數量 .count

print("共有 \(airports.count) 個機場")

檢查是否為空 .isEmpty

if airports.isEmpty {
    print("字典是空的")
}

新增或更新值 .updateValue

使用下標語法 (Subscript Syntax):

// 新增一個新的鍵值對
airports["LHR"] = "London"

// 更新現有的鍵值對
airports["LHR"] = "London Heathrow"

你也可以使用 updateValue(_:forKey:) 方法,它的好處是會回傳更新前的舊值 (如果有的話),這對於檢查更新是否成功很有用。

if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") {
    print("原本的值是 \(oldValue),現在更新了")
}

移除值 .removeValue

將某個鍵的值設為 nil 即可移除該鍵值對:

airports["APL"] = "Apple International"
airports["APL"] = nil // "APL" 被移除了

或者使用 removeValue(forKey:)

if let removedValue = airports.removeValue(forKey: "DUB") {
    print("移除了 \(removedValue)")
}

遍歷字典

使用 for-in 迴圈遍歷字典,每次迭代會得到一個 (key, value) 的元組:

for (airportCode, airportName) in airports {
    print("\(airportCode): \(airportName)")
}

如果你只想遍歷所有的鍵或所有的值 .keys .values

for code in airports.keys {
    print("Airport code: \(code)")
}

for name in airports.values {
    print("Airport name: \(name)")
}