来存储相同类型并且没有确定顺序的值。
当集合元素顺序不重要时或者希望确保每个元素只出现一次时可以使用集合而不是数组。
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
极客学院 - 集合