來存儲相同類型并且沒有確定順序的值。
當集合元素順序不重要時或者希望確保每個元素只出現一次時可以使用集合而不是數組。
1.定義
//空集合
var tempSet = Set<Character>()
//字面量創建
var tempSet1 :Set<String> = ["a","b","c"]
var tempSet2 :Set = ["a","b","c"]
2.長度
var tempSet3 :Set = ["a","b","c"]
print(tempSet3.count) //3
3.是否為空
var tempSet4 :Set<String> = []
if tempSet4.isEmpty{
print("集合為空") //集合為空
}
4.增
若插入的元素在集合有,則集合不變;若插入的元素集合中沒有,則添加
var tempSet3 :Set = ["a","b","c"]
tempSet3.insert("a")
print(tempSet3) //["b", "a", "c"]
tempSet3.insert("d")
print(tempSet3) //["b", "a", "d", "c"]
5.刪
刪除元素,并返回對應的元素;若集合中沒有,則返回nil
var tempSet3 :Set = ["a","b","c","d"]
tempSet3.remove("d")
print(tempSet3) // ["b", "a", "c"]
6.查
var tempSet3 :Set = ["a","b","c","d"]
if tempSet3.contains("b"){
print("集中中有 b 元素")
}
7.遍歷
var tempSet3 :Set = ["a","b","c"]
for item in tempSet3{
print("\(item)")
}
//b
//a
//c
8.排序
為了按照特定順序來遍歷一個Set中的值可以使用sorted()方法,
它將返回一個有序數組,這個數組的元素排列順序由操作符'<'對元素進行比較的結果來確定.
var tempSet3 :Set = ["b","c","a"]
for item in tempSet3.sorted(){
print("\(item)")
}
//a
//b
//c
9.集合之間的操作
使用intersection(_:): 交集
使用union(_:): 并集
使用symmetricDifference(_:)方法根據在一個集合中但不在兩個集合中的值創建一個新的集合。
使用subtracting(_:)方法根據不在該集合中的值創建一個新的集合。
let oddDigits: Set = [1, 3, 5, 7, 9]
let evenDigits: Set = [0, 2, 4, 6, 8]
let singleDigitPrimeNumbers: Set = [2, 3, 5, 7]
oddDigits.union(evenDigits).sorted()
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
oddDigits.intersection(evenDigits).sorted()
// []
oddDigits.subtracting(singleDigitPrimeNumbers).sorted()
// [1, 9]
oddDigits.symmetricDifference(singleDigitPrimeNumbers).sorted()
// [1, 2, 9]
10.集合成員關系和相等
使用“是否相等”運算符(==)來判斷兩個集合是否包含全部相同的值。
使用isSubset(of:)方法來判斷一個集合中的值是否也被包含在另外一個集合中。
使用isSuperset(of:)方法來判斷一個集合中包含另一個集合中所有的值。
使用isStrictSubset(of:)或者isStrictSuperset(of:)方法來判斷一個集合是否是另外一個集合的子集合或者父集合并且兩個集合并不相等。
使用isDisjoint(with:)方法來判斷兩個集合是否不含有相同的值(是否沒有交集)。
let houseAnimals: Set = ["??", "??"]
let farmAnimals: Set = ["??", "??", "??", "??", "??"]
let cityAnimals: Set = ["??", "??"]
houseAnimals.isSubset(of: farmAnimals) // true
farmAnimals.isSuperset(of: houseAnimals) // true
farmAnimals.isDisjoint(with: cityAnimals) // true
極客學院 - 集合