Swift 中的集合类型有哪些?Array、Set 和 Dictionary 有什么区别和适用场景?
Swift 提供了三种主要的集合类型:Array(数组)、Set(集合)和 Dictionary(字典)。每种集合类型都有其特定的用途和特点。
Array(数组):
- 有序集合
- 可以包含重复元素
- 可以通过索引访问元素
- 示例:
swift
var numbers = [1, 2, 3, 4, 5] numbers.append(6) numbers[0] = 10 let first = numbers.first // Optional(10) let count = numbers.count // 6
Array 的常用操作:
swiftvar array = [1, 2, 3] // 添加元素 array.append(4) array.insert(0, at: 0) // 删除元素 array.remove(at: 0) array.removeLast() // 查找元素 let index = array.firstIndex(of: 2) // 排序 array.sort() let sorted = array.sorted() // 遍历 for (index, element) in array.enumerated() { print("\(index): \(element)") }
Set(集合):
- 无序集合
- 不能包含重复元素
- 元素必须是可哈希的
- 示例:
swift
var set: Set<Int> = [1, 2, 3, 4, 5] set.insert(6) set.contains(3) // true let count = set.count // 6
Set 的常用操作:
swiftvar set1: Set<Int> = [1, 2, 3, 4, 5] var set2: Set<Int> = [4, 5, 6, 7, 8] // 集合操作 let union = set1.union(set2) // {1, 2, 3, 4, 5, 6, 7, 8} let intersection = set1.intersection(set2) // {4, 5} let difference = set1.subtracting(set2) // {1, 2, 3} let symmetricDifference = set1.symmetricDifference(set2) // {1, 2, 3, 6, 7, 8} // 检查关系 set1.isSubset(of: set2) // false set1.isSuperset(of: set2) // false set1.isDisjoint(with: set2) // false // 添加和删除 set1.insert(6) set1.remove(1)
Dictionary(字典):
- 无序键值对集合
- 键必须是唯一的
- 键必须是可哈希的
- 示例:
swift
var dict = ["name": "John", "age": "30"] dict["email"] = "john@example.com" dict["name"] = "Jane" let name = dict["name"] // Optional("Jane") let count = dict.count // 3
Dictionary 的常用操作:
swiftvar dict = ["name": "John", "age": "30"] // 添加和更新 dict["email"] = "john@example.com" dict.updateValue("Jane", forKey: "name") // 删除 dict.removeValue(forKey: "age") // 访问 if let name = dict["name"] { print(name) } // 遍历 for (key, value) in dict { print("\(key): \(value)") } // 获取所有键和值 let keys = Array(dict.keys) let values = Array(dict.values)
Array、Set 和 Dictionary 的区别:
-
有序性:
- Array:有序
- Set:无序
- Dictionary:无序(键值对)
-
重复元素:
- Array:可以包含重复元素
- Set:不能包含重复元素
- Dictionary:键必须唯一,值可以重复
-
访问方式:
- Array:通过索引访问
- Set:通过成员检查访问
- Dictionary:通过键访问
-
性能:
- Array:插入和删除 O(n),访问 O(1)
- Set:插入、删除、查找 O(1)
- Dictionary:插入、删除、查找 O(1)
适用场景:
-
使用 Array 的场景:
- 需要保持元素顺序
- 允许重复元素
- 需要通过索引访问元素
- 示例:待办事项列表、历史记录
-
使用 Set 的场景:
- 需要确保元素唯一性
- 需要快速查找元素是否存在
- 需要集合操作(并集、交集等)
- 示例:标签、用户 ID 集合
-
使用 Dictionary 的场景:
- 需要通过键快速查找值
- 需要存储键值对数据
- 键是唯一的
- 示例:用户信息、配置选项
最佳实践:
- 根据需求选择合适的集合类型
- 使用 Array 保持顺序
- 使用 Set 确保唯一性
- 使用 Dictionary 存储键值对
- 注意集合的性能特性