Dictionary
声明
@frozen struct Dictionary<Key, Value> where Key : Hashable
概述
字典是一种哈希表,提供对其包含的条目的快速访问。表中的每个条目都使用其键标识,键是可散列的类型,例如字符串或数字。您使用该键来检索相应的值,该值可以是任何对象。在其他语言中,类似的数据类型称为散列或关联数组。
使用字典文字创建一个新字典。字典文字是逗号分隔的键值对列表,其中冒号将每个键与其关联的值分开,并用方括号括起来。您可以将字典文字分配给变量或常量,或将其传递给需要字典的函数。
以下是创建 HTTP 响应代码及其相关消息的字典的方法:
var responseMessages = [200: "OK",
403: "Access forbidden",
404: "File not found",
500: "Internal server error"]
responseMessages
变量被推断为具有类型 [Int: String]
。字典的 Key
类型是 Int
,字典的 Value
类型是 String
。
要创建没有键值对的字典,请使用空字典文字 ([:]
)。
var emptyDict: [String: String] = [:]
任何符合 Hashable
协议的类型都可以用作字典的 Key
类型,包括 Swift 的所有基本类型。通过使它们符合Hashable
协议,您可以使用自己的自定义类型作为字典键。
获取和设置字典值
访问字典中值的最常见方法是使用键作为下标。使用键下标采用以下形式:
print(responseMessages[200])
// Prints "Optional("OK")"
使用键为字典下标会返回一个可选值,因为字典可能不包含您在下标中使用的键的值。
下一个示例使用 responseMessages
字典的基于键的下标,其中两个键存在于字典中,一个键不存在。
let httpResponseCodes = [200, 403, 301]
for code in httpResponseCodes {
if let message = responseMessages[code] {
print("Response \(code): \(message)")
} else {
print("Unknown response \(code)")
}
}
// Prints "Response 200: OK"
// Prints "Response 403: Access forbidden"
// Prints "Unknown response 301"
您还可以使用基于键的下标更新、修改或删除字典中的键和值。要添加新的键值对,请将值分配给尚未成为字典一部分的键。
responseMessages[301] = "Moved permanently"
print(responseMessages[301])
// Prints "Optional("Moved permanently")"
通过将新值分配给字典中已存在的键来更新现有值。如果您将 nil
分配给现有键,则会删除该键及其关联值。以下示例将404
代码的值更新为简单的“Not found”,并完全删除500
代码的键值对。
responseMessages[404] = "Not found"
responseMessages[500] = nil
print(responseMessages)
// Prints "[301: "Moved permanently", 200: "OK", 403: "Access forbidden", 404: "Not found"]"
在可变的 Dictionary
实例中,您可以就地修改您通过键控下标访问的值。下面的代码示例声明了一个名为 interestingNumbers
的字典,其中包含整数数组的字符串键和值,然后按降序对每个数组进行就地排序。
var interestingNumbers = ["primes": [2, 3, 5, 7, 11, 13, 17],
"triangular": [1, 3, 6, 10, 15, 21, 28],
"hexagonal": [1, 6, 15, 28, 45, 66, 91]]
for key in interestingNumbers.keys {
interestingNumbers[key]?.sort(by: >)
}
print(interestingNumbers["primes"]!)
// Prints "[17, 13, 11, 7, 5, 3, 2]"
迭代字典的内容
每个字典都是键值对的无序集合。您可以使用 for
- in
循环遍历字典,将每个键值对分解为元组的元素。
let imagePaths = ["star": "/glyphs/star.png",
"portrait": "/images/content/portrait.jpg",
"spacer": "/images/shared/spacer.gif"]
for (name, path) in imagePaths {
print("The path to '\(name)' is '\(path)'.")
}
// Prints "The path to 'star' is '/glyphs/star.png'."
// Prints "The path to 'portrait' is '/images/content/portrait.jpg'."
// Prints "The path to 'spacer' is '/images/shared/spacer.gif'."
字典中键值对的顺序在突变之间是稳定的,但在其他方面是不可预测的。如果您需要键值对的有序集合并且不需要Dictionary
提供的快速键查找,请参阅KeyValuePairs
类型以获取替代方案。
您可以使用默认实现提供的 contains(where:)
或 firstIndex(where:)
方法在字典的内容中搜索特定值。以下示例检查 imagePaths
是否包含 "/glyphs"
目录中的任何路径:
let glyphIndex = imagePaths.firstIndex(where: { $0.value.hasPrefix("/glyphs") })
if let index = glyphIndex {
print("The '\(imagePaths[index].key)' image is a glyph.")
} else {
print("No glyphs found!")
}
// Prints "The 'star' image is a glyph.")
请注意,在此示例中,imagePaths
使用字典索引进行下标。与基于键的下标不同,基于索引的下标将对应的键值对作为非可选元组返回。
print(imagePaths[glyphIndex!])
// Prints "(key: "star", value: "/glyphs/star.png")"
只要字典有足够的容量来存储添加的值而不分配更多缓冲区,字典的索引在添加到字典时保持有效。当字典超出其缓冲区时,现有索引可能会在没有任何通知的情况下失效。
当您知道要向字典添加多少新值时,请使用 init(minimumCapacity:)
初始化程序分配正确数量的缓冲区。
字典和 NSDictionary 之间的桥接
您可以使用as
运算符在Dictionary
和NSDictionary
之间进行桥接。为了使桥接成为可能,字典的Key
和Value
类型必须是类、@objc
协议或桥接到 Foundation 类型的类型。
从 Dictionary
到 NSDictionary
的桥接总是需要 O(1) 的时间和空间。当字典的 Key
和 Value
类型既不是类也不是 @objc
协议时,任何必需的元素桥接都会在第一次访问每个元素时发生。因此,使用字典内容的第一个操作可能需要 O(n
)。
从NSDictionary
到Dictionary
的桥接首先调用字典上的copy(with:)
方法(Objective-C 中的- copyWithZone:
)以获取不可变副本,然后执行额外的 Swift 簿记工作,这需要 O(1) 时间。对于已经不可变的NSDictionary
的实例,copy(with:)
通常在 O(1) 时间内返回相同的字典;否则,复制性能未指定。 NSDictionary
和 Dictionary
的实例使用相同的 copy-on-write 优化来共享缓冲区,这与 Dictionary
的两个实例共享缓冲区时使用的相同。
可用版本
相关用法
- Swift Dictionary.Keys shuffled()用法及代码示例
- Swift Dictionary.Keys.Iterator next()用法及代码示例
- Swift Dictionary.Keys dropFirst(_:)用法及代码示例
- Swift Dictionary allSatisfy(_:)用法及代码示例
- Swift Dictionary.Index ..<(_:_:)用法及代码示例
- Swift Dictionary values用法及代码示例
- Swift Dictionary dropFirst(_:)用法及代码示例
- Swift Dictionary firstIndex(where:)用法及代码示例
- Swift Dictionary first(where:)用法及代码示例
- Swift Dictionary.Keys firstIndex(where:)用法及代码示例
- Swift Dictionary.Values min(by:)用法及代码示例
- Swift Dictionary.Keys description用法及代码示例
- Swift Dictionary.Index ...(_:_:)用法及代码示例
- Swift Dictionary merge(_:uniquingKeysWith:)用法及代码示例
- Swift Dictionary.Keys contains(_:)用法及代码示例
- Swift Dictionary.Keys reduce(_:_:)用法及代码示例
- Swift Dictionary.Keys first用法及代码示例
- Swift Dictionary.Index ...(_:)用法及代码示例
- Swift Dictionary subscript(_:default:)用法及代码示例
- Swift Dictionary.Values prefix(upTo:)用法及代码示例
- Swift Dictionary.Keys suffix(_:)用法及代码示例
- Swift Dictionary isEmpty用法及代码示例
- Swift Dictionary.Keys prefix(_:)用法及代码示例
- Swift Dictionary.Values min()用法及代码示例
- Swift Dictionary reduce(_:_:)用法及代码示例
注:本文由纯净天空筛选整理自apple.com大神的英文原创作品 Dictionary。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。