昨天我們認識了 Set
,它擅長管理「不重複」的資料。但真實世界的資訊往往是成對出現的,例如:想透過「人名」查「電話號碼」,或是用「機場代碼」找「城市名稱」。
當你需要用一個獨特的標籤 (Key) 來快速查找對應的資料 (Value) 時,今天的主角——字典 (Dictionary),它讓你能建立強大的「鍵值配對」關係,用最直覺的方式來組織和查詢結構化資料。
[:]
及用字面量建立字典[key]
進行新增、修改、查詢與刪除.keys
)或值(.values
).count
和 .isEmpty
檢查字典狀態。在 Swift 中,所有基本型別,如 String
, Int
, Double
, Bool
等,都預設是可雜湊的,所以可以直接當作字典的鍵。
而字典的使用語法以[KeyType: ValueType]
或Dictionary<Key, Value>
表示,鍵與值的型別可以不同,例如:
var countryCodes: [String: String] // 鍵為 String,值為 String
var productPrices = [String: Int]() // 空字典,鍵為 String,值為 Int
// 帶初始值的字典
var airportMap: [String: String] = [
"TYO": "Tokyo",
"DUB": "Dublin"
]
// 設為空字典
airportMap = [:] // 鍵值對全部清空
字典也有跟陣列、集合一樣的基本屬性:
var inventory: [String: Int] = ["Laptop": 5, "Keyboard": 10]
print(inventory.count) // 印出 2(字典中鍵值對的數量)
print(inventory.isEmpty) // 印出 false(字典不是空的)
使用下標語法 dictionary[key]
就能操作值,新增與修改共用語法:
var studentGrades = ["Alice": 95, "Bob": 88]
// 新增(若鍵不存在)
studentGrades["Charlie"] = 77
// 修改(若鍵存在)
studentGrades["Bob"] = 90
// 查詢(結果為 Optional)
let alicesGrade = studentGrades["Alice"] // Optional(95)
let davidsGrade = studentGrades["David"] // nil
// 刪除(將值設為 nil)
studentGrades["Charlie"] = nil
除了使用下標語法,還可以用方法來進一步操作字典:
var fruitPrices = ["Apple": 30, "Banana": 20]
// 使用 if let 安全解包
// 更新 Apple 的價格
if let oldApplePrice = fruitPrices.updateValue(35, forKey: "Apple") {
print(oldApplePrice) // 印出 30
}
// 移除 Banana
if let removedBananaPrice = fruitPrices.removeValue(forKey: "Banana") {
print(removedBananaPrice) // 印出 20
}
有跟上實作的朋友可能會疑問,為何print(oldApplePrice)
印出來的是30
,而不是更新後的35
?
我覺得產生這個疑問非常好,因為這正是updateValue
方法的核心設計!答案就是:
updateValue
方法回傳的是被它替換掉的「舊值」,而不是新值。
你可以把這個過程想像成去店裡 「換貨」:
所以,if let oldApplePrice = ...
這行程式碼中,你用來接住回傳值的 oldApplePrice
常數,拿到的自然就是那個被換下來的舊價格 30
。
那該如何驗證字典真的更新了?
我們可以嘗試印出整個字典來確認。你會發現,字典本身確實已經更新成新值了:
var fruitPrices = ["Apple": 30, "Banana": 20]
if let oldApplePrice = fruitPrices.updateValue(35, forKey: "Apple") {
print("Apple 的舊價格是 \(oldApplePrice)") // 印出 Apple 的舊價格是 30
}
// 檢查字典現在的狀態
print(fruitPrices) // 會印出 ["Apple": 35, "Banana": 20]
你看,字典裡的價格確實變成35
了!
這樣設計的好處是,有時候我們在更新資料時,也想知道它原本是多少,方便做紀錄或比較,updateValue
就貼心地幫我們做好了這件事。
使用 for-in
可遍歷整個字典,也可僅列出鍵或值:
let travelDestinations = ["NYC": "New York City", "LAX": "Los Angeles"]
// 遍歷鍵值對(順序不固定)
for (code, name) in travelDestinations {
print("Airport Code: \(code), City: \(name)")
}
/* 輸出:
Airport Code: LAX, City: Los Angeles
Airport Code: NYC, City: New York City
*/
// 遍歷所有鍵
for code in travelDestinations.keys {
print("Airport Code: \(code)")
}
/* 輸出:
Airport Code: LAX
Airport Code: NYC
*/
// 遍歷所有值
for name in travelDestinations.values {
print("City Name: \(name)")
}
/* 輸出:
City Name: Los Angeles
City Name: New York City
*/
// 排序後輸出
let sortedCodes = Array(travelDestinations.keys).sorted()
print(sortedCodes) // 印出 ["LAX", "NYC"]
今天我們攻克了 Swift 中處理「鍵值配對」的利器:字典(Dictionary)!我們從如何宣告與建立字典開始,接著掌握了透過下標語法[key]
來快速查詢、修改與刪除資料的核心技巧,也認識了updateValue()
等替代方法。
此外,我們還學會了如何靈活地遍歷所有鍵值對、或單獨取出.keys
與.values
。當需要依照某個「識別碼」快速找到對應資料時,字典會是我們很重要的夥伴!
我們的程式到目前為止都只會一步步往下執行,但如何讓它變得「聰明」,能夠根據不同情況做出不同反應?
例如,如何判斷使用者是否成年、或根據分數給出「及格/不及格」的評語?明天,我們將學習賦予程式「思考能力」的兩大神器:if
與switch
。你將學會如何設定條件,讓程式在遇到岔路時知道該走哪條路,從簡單的是非題到複雜的多重選擇題,一次搞定!
敬請期待《Day 9|Swift:條件判斷超入門!搞懂 if 和 switch 就靠這一課!》