Swift 字典
Swift 字典
Swift 字典表示无序的键值对的集合,其中每个键都唯一对应一个值。
Swift 字典可以通过以下方式创建:
var emptyDict = [String: Int]() // 创建一个空的字典
var cities = ["Shanghai": 1_0000_0000, "New York": 8_0080_0] // 创建和初始化一个字典
字典中键的类型必须是可哈希的,这意味着它们必须提供 hashValue
属性。所有的 Swift 基本类型均可哈希,并且实现了 Hashable
协议。
字典操作
通过下标访问或者修改字典中特定键对应的值:
var cityPopulation = ["Shanghai": 1_0000_0000, "New York": 8_0080_0]
let shanghaiPopulation = cityPopulation["Shanghai"] // 访问某个键对应的值
cityPopulation["Beijing"] = 7_1500_0000 // 修改某个键对应的值
使用下面的方法可以从字典中移除特定的键值对:
cityPopulation["Shanghai"] = nil // 删除某个键对应的值
cityPopulation.removeValue(forKey: "New York") // 移除某个键值对
cityPopulation.removeAll() // 移除所有键值对
使用 count
属性来获取字典中键值对的数量:
var cityPopulation = ["Shanghai": 1_0000_0000, "New York": 8_0080_0]
print(cityPopulation.count) // 输出 2
字典遍历
Swift 字典遍历有以下三种方法:
- 遍历字典中所有键和值。使用
for-in
循环,每个键值对被表示为一个(key, value)
元组:
var cityPopulation = ["Shanghai": 1_0000_0000, "New York": 8_0080_0]
for (city, population) in cityPopulation {
print("\(city) has a population of \(population) people.")
}
- 遍历字典中的键。使用
keys
属性能够获取所有的键,并通过for-in
循环打印每一个键:
var cityPopulation = ["Shanghai": 1_0000_0000, "New York": 8_0080_0]
for city in cityPopulation.keys {
print(city)
}
- 遍历字典中的值。使用
values
属性能够获取所有的值,并通过for-in
循环打印每一个值:
var cityPopulation = ["Shanghai": 1_0000_0000, "New York": 8_0080_0]
for population in cityPopulation.values {
print(population)
}
总结
Swift 字典利用键值对将数据组合起来,并且提供了一系列方便的操作方法。本文简要介绍了什么是 Swift 字典,以及如何创建、访问、修改和删除字典中的键值对。同时,我们也介绍了如何使用不同的方式遍历 Swift 字典。