集合(Set)
- 定義:Set<元素類型>,無法使用類型推斷,可省略類型
let num : Set = [1, 2, 3, 1, 4] //{1,2,3,4}
let citys : Set = ["Beijing", "Shanghai", "Guangzhou", "Shenzhen"]
- ①元素計數(shù):count,是否為空:isEmpty
citys.count //4
citys.isEmpty //false
citys.insert("Changsha")
citys.remove("Changsha")
citys.contains("Beijing")
- ⑤轉(zhuǎn)換成數(shù)組:sorted
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) //結(jié)果賦值給x:{1, 2}
x.union(y) //結(jié)果賦值給x:{1,2,3,4,5,6}
- 4??補集 symmetricDifference
x.symmetricDifference(y) //結(jié)果賦值給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