集合(Set)
- 定义:Set<元素类型>,无法使用类型推断,可省略类型
let num : Set = [1, 2, 3, 1, 4] //{1,2,3,4}
let citys : Set = ["Beijing", "Shanghai", "Guangzhou", "Shenzhen"]
citys.count //4
citys.isEmpty //false
citys.insert("Changsha")
citys.remove("Changsha")
citys.contains("Beijing")
let cityArray = citys.sorted() //["Beijing", "Guangzhou", "Shanghai", "Shenzhen"]
集合间的运算:交差并补
var x :Set = [1, 2, 3, 4]
let y :Set = [3, 4, 5, 6]
x.intersection(y) // {3, 4}
x.subtract(y) //结果赋值给x:{1, 2}
x.union(y) //结果赋值给x:{1,2,3,4,5,6}
- 4⃣️补集 symmetricDifference
x.symmetricDifference(y) //结果赋值给x:{1,2,5,6}
- 子集:isSubset(可以相等),严格子集isStrictSubset
let a :Set = [1, 2, 3]
let b :Set = [3, 2, 1]
let c :Set = [1, 2, 3, 4]
a.isSubset(of: b) // true
a.isStrictSubset(of: b) // false
a.isStrictSubset(of: c) // true
- 父集:isSupersetOf(可以相等),严格父集isStrictSuperSetOf
- 无交集:isDisjoint
let j : Set = ["游戏", "动漫"]
let k: Set = ["吃", "睡"]
j.isDisjoint(with: k) //true