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