集合的初始化必须显式声明类型,不然会被认为是数组。
//var fruitSet : Set<String> = ["apple", "grape", "banana"]
//var fruitSet = Set(["apple", "grape", "banana"])
//var fruitSet : Set = ["apple", "grape", "banana"]
空集合
var emptySet : Set<String> = []
var emptySet = Set<String>()
集合的增删改查
获取元素个数
var fruitSet : Set = ["apple", "grape", "banana", "orange", "apple"]
//注:集合中的重复元素是无效的,这点有区别于数组
fruitSet.count //4
判空
fruitSet.isEmpty //false
emptySet.isEmpty //true
包含
fruitSet.contains("grape") //true
fruitSet.contains("lemon") //false
遍历
for fruit in fruitSet {
print(fruit)
}
比较
var fruitSet2 : Set = ["apple", "banana", "grape", "orange"]
fruitSet2 == fruitSet //true
//集合Set中的元素是无序的,这点也是有区别于数组的
添加元素
fruitSet.insert("mongo") //["apple", "grape", "banana", "orange", "mongo"]
fruitSet.insert("mongo") //由于集合中的元素是不会重复的,所以重复添加无效
删除元素
fruitSet.remove("orange") //["apple", "grape", "banana", "mongo"]
//remove()函数返回值为可选型
if let fruit = fruitSet.remove("orange") {
print("orange is removed")
}
else {
print("orange 不存在")
//如果删除不存在的元素,remove()函数返回值为nil
}
//清空
//fruitSet.removeAll()
集合的运算
只有两个集合的元素类型相同时,才能进行下面的各种运算,否则会报错。
并
var set1: Set = ["apple", "milk", "oat"]
var set2: Set = ["apple", "rice", "milk"]
//union()函数并不会改变set1和set2,而是会产生一个新的Set
var set3:Set = set1.union(set2) //["apple", "milk", "oat", "rice"]
交
var set1: Set = ["apple", "milk", "oat"]
var set2: Set = ["apple", "rice", "milk"]
var set3:Set = set1.intersection(set2) //["apple", "milk"]
减
var set1: Set = ["apple", "milk", "oat"]
var set2: Set = ["apple", "rice", "milk"]
//suntract()函数没有返回值,直接修改set1
set1.subtract(set2) //["oat"]
异或(A异或B,即A并B - A交B)
var set1: Set = ["apple", "milk", "oat"]
var set2: Set = ["apple", "rice", "milk"]
var set3:Set = set1.symmetricDifference(set2) //["oat", "rice"]
集合之间的关系判断
相离(两个集合是否有交集)
var set1: Set = ["apple", "milk", "oat"]
var set2: Set = ["apple", "rice", "milk"]
var set3:Set = ["cake", "biscuit"]
set1.isDisjoint(with: set2) //false
set1..isDisjoint(with: set3) //true
子集与超子集
A是B的子集,即B包含A中的所有元素
A是B的超子集,即B包含A中的所有元素(A是B的子集),且A与B不相等
var set1: Set = ["apple", "milk", "oat"]
var set2: Set = ["apple", "milk"]
var set3: Set = ["apple", "milk", "oat"]
var set4: Set = ["apple", "egg"]
//判断set1是否是set3的子集
set1.isSubset(of: set3) //true
set3.isSuperset(of: set1) //true
//判断set2是否是set1的超子集
set1.isStrictSuperset(of: set2) //true
set2.isStrictSubset(of: set1) //true
set1.isSuperset(of: set2) //true
set2.isSuperset(of: set4) //false