Z
ZHANK
集合类型

集合 Set

Set 去重/高效查找、intersection/union 运算、isSubset/isSuperset

集合 Set

Set 存储唯一值、查找 O(1)——适合去重、成员判断、集合运算。

学完本章你将: 掌握 Set 去重/高效查找、集合运算。


创建与操作

swift
var fruits: Set = ["apple", "banana", "cherry"]
fruits.insert("durian")
fruits.remove("banana")

fruits.contains("apple")  // true
fruits.count              // 3

集合运算

swift
let a: Set = [1, 2, 3, 4]
let b: Set = [3, 4, 5, 6]

a.intersection(b)      // [3, 4]——交集
a.union(b)             // [1,2,3,4,5,6]——并集
a.subtracting(b)       // [1, 2]——差集
a.symmetricDifference(b) // [1,2,5,6]——对称差

a.isSubset(of: b)      // a 是 b 的子集?
a.isSuperset(of: b)    // a 是 b 的超集?

数组去重

swift
let nums = [1, 2, 2, 3, 3, 3]
let unique = Array(Set(nums))  // [1,2,3]——顺序不保证