Swift 集合 (Sets)
集合 (Set) 用來儲存相同型別但沒有順序且唯一的值。
當元素的順序不重要,或者你需要確保每個元素只出現一次時,就應該使用 Set 而不是 Array。
Hashable 協議
為了能被儲存在 Set 中,該型別必須遵循 Hashable 協議。幸運的是,Swift 的基本型別 (如 String, Int, Double, Bool) 預設都是 Hashable 的。
建立集合
與陣列不同,Set 沒有專屬的簡化語法,你需要顯式地宣告型別為 Set。
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
建立空集合:
var letters = Set<Character>()
print("letters 的數量:\(letters.count)")
存取與修改集合
插入與刪除 .insert .remove
favoriteGenres.insert("Jazz")
// 如果 "Jazz" 已經存在,這裡什麼都不會發生 (也不會報錯)
if let removedGenre = favoriteGenres.remove("Rock") {
print("\(removedGenre) 被移除了")
} else {
print("集合中沒有 Rock")
}
檢查是否包含 .contains
if favoriteGenres.contains("Funk") {
print("有 Funk 音樂")
} else {
print("沒有 Funk 音樂")
}
集合運算 (Set Operations)
Set 最強大的地方在於支援數學上的集合運算,如交集、聯集、差集等。
假設我們有兩個集合:
let oddDigits: Set = [1, 3, 5, 7, 9]
let evenDigits: Set = [0, 2, 4, 6, 8]
let singleDigitPrimes: Set = [2, 3, 5, 7]
聯集 .union
兩個集合合併:
oddDigits.union(evenDigits).sorted()
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
交集 .intersection
兩個集合都有的部分:
oddDigits.intersection(evenDigits).sorted()
// [] (空集合)
差集 .subtracting
在 A 集合但不在 B 集合的部分:
oddDigits.subtracting(singleDigitPrimes).sorted()
// [1, 9]
對稱差集 .symmetricDifference
只存在於其中一個集合,不同時存在於兩者的部分 (A 聯集 B 減去 A 交集 B):
oddDigits.symmetricDifference(singleDigitPrimes).sorted()
// [1, 2, 9]