Appearance
Swift 入门(5):集合类型(Array、Set、Dictionary)
Swift 提供了三种常用集合类型:数组(Array)、集合(Set) 和 字典(Dictionary)。掌握它们就能处理大部分数据存储与操作。
数组(Array)
数组是有序的元素集合,可以包含重复值。
swift
var numbers: [Int] = [1, 2, 3, 4]
// 添加元素
numbers.append(5)
// 访问元素
print(numbers[0]) // 1
// 遍历
for num in numbers {
print(num)
}简写:
swift
let fruits = ["Apple", "Banana", "Cherry"]
print(fruits.count) // 3
print(fruits.contains("Banana")) // true集合(Set)
集合是 无序且唯一 的元素集合。
swift
var set: Set<String> = ["A", "B", "C"]
set.insert("D")
set.insert("A") // 已存在,不会重复
print(set.contains("C")) // true
// 遍历(顺序不保证)
for item in set {
print(item)
}集合常用于 去重:
swift
let nums = [1, 2, 2, 3, 3, 4]
let uniqueNums = Set(nums)
print(uniqueNums) // {2, 3, 1, 4}字典(Dictionary)
字典是 键值对 的集合。
swift
var dict: [String: Int] = [
"Alice": 25,
"Bob": 30
]
// 访问
print(dict["Alice"]) // Optional(25)
// 修改
dict["Alice"] = 26
// 新增
dict["Charlie"] = 22
// 遍历
for (name, age) in dict {
print("\(name): \(age)")
}集合运算(Set 特有)
swift
let set1: Set = [1, 2, 3]
let set2: Set = [3, 4, 5]
// 交集
print(set1.intersection(set2)) // [3]
// 并集
print(set1.union(set2)) // [1, 2, 3, 4, 5]
// 差集
print(set1.subtracting(set2)) // [1, 2]小结
- Array:有序,可重复 → 适合顺序存储。
- Set:无序,唯一 → 适合去重、集合运算。
- Dictionary:键值对 → 适合映射关系。