【iOS 中文開放式課程】集合型態 集合 (Sets) (Part 2)
我們需要您的贊助
集合操作
初始集合資料
//宣告一組,奇數數字 Set 集合
let a: Set = [1, 3, 5, 7, 9]
//宣告一組,偶數數字 Set 集合
let b: Set = [0, 2, 4, 6, 8]
//宣告一組,Set 集合
let c: Set = [2, 3, 5, 7]
intersection
創建一個新的 Set 集合,內容包含你有我也有的值。
(swift 2 為 intersect,swift 3 改名為 intersection 同用法)
(swift 2 為 intersect,swift 3 改名為 intersection 同用法)
print(a.intersection(b).sorted())
// []
//沒有任何內容,因為兩個 Set 沒有任何交集的內容
symmetricDifference
創建一個新的 Set 集合,內容僅包你有我沒有和我有你沒有的值。(swift 2 為 exclusiveOr,swift 3 改名為 symmetricDifference 同用法)
print(a.symmetricDifference(c).sorted())
// [1, 2, 9]
// 因為兩個 Set 都有 3,5,7
// 所以返回兩個 Set 中 除了這三個值以外的值
union
創建一個新的 Set 集合,其內容的值包含兩個 Set 中所有的值。
print(a.union(b).sorted())
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 包含兩個 Set 中所有的值
subtracting
創建一個新的 Set 集合,其內的值在一個 Set 內,但不在另一個 Set 內。
(swift 2 為 subtract,swift 3 改名為 subtracting 同用法)
(swift 2 為 subtract,swift 3 改名為 subtracting 同用法)
print(a.subtracting(c).sorted())
// [1, 9] 因為 3,5,7 在 c 內
// 所以返回 a 中 除了這三個值之外的值
集合成員關係
初始化集合資料
let houseAnimals: Set = ["狗", "貓"]
let farmAnimals: Set = ["牛", "雞", "羊", "狗", "貓"]
let cityAnimals: Set = ["鳥", "鼠"]
==
使用運算符號(==),來判斷兩個集合是否包含全部相同的值。
print(houseAnimals==farmAnimals)
isSubset
使用isSubset(of:)方法來判斷一個集合中的值是否也被包含在另外一個集合中。
print(houseAnimals.isSubset(of: farmAnimals))
// true
isSuperset
使用isSuperset(of:)方法來判斷一個集合中包含另一個集合中所有的值。
print(farmAnimals.isSuperset(of: houseAnimals))
// true
isStrictSubset
使用 isStrictSubset(of:)或者isStrictSuperset(of:)方法來判斷一個集合是否是另外一個集合的子集合或者父集合併且兩個集合併不相等。
isDisjoint
使用 isDisjoint(with:)方法來判斷兩個集合是否不含有相同的值(是否沒有交集)。
print(farmAnimals.isDisjoint(with: cityAnimals))
// true
參考資料: