主题
集合(Set)
集合是存储唯一且无序元素的数据结构,适合用于去重和快速查找。
创建集合
swift
var numbers: Set<Int> = [1, 2, 3, 4, 5]
var fruits: Set = ["苹果", "香蕉", "橘子"] // 类型推断为 Set<String>
添加与删除元素
swift
fruits.insert("葡萄")
fruits.remove("香蕉")
判断元素是否存在
swift
if fruits.contains("苹果") {
print("集合中包含苹果")
}
遍历集合
swift
for fruit in fruits {
print(fruit)
}
集合运算
支持交集、并集和差集:
swift
let a: Set = [1, 2, 3]
let b: Set = [2, 3, 4]
print(a.union(b)) // 并集
print(a.intersection(b)) // 交集
print(a.subtracting(b)) // 差集
集合结构适用于需要唯一性和集合关系操作的场景。