结构
Key
KeyValuePairs
一个轻量级的键值对集合。
声明
@frozen struct KeyValuePairs<Key, Value>
概述
当您需要键值对的有序集合并且不需要 Dictionary
类型提供的快速键查找时,请使用 KeyValuePairs
实例。与真正字典中的键值对不同,KeyValuePairs
实例的键和值都必须符合 Hashable
协议。
您使用 Swift 字典文字初始化 KeyValuePairs
实例。除了保持原始字典文字的顺序外,KeyValuePairs
还允许重复键。例如:
let recordTimes: KeyValuePairs = ["Florence Griffith-Joyner": 10.49,
"Evelyn Ashford": 10.76,
"Evelyn Ashford": 10.79,
"Marlies Gohr": 10.81]
print(recordTimes.first!)
// Prints "(key: "Florence Griffith-Joyner", value: 10.49)"
使用 KeyValuePairs
时,某些对字典有效的操作会变慢。特别是,要找到与键匹配的值,您必须搜索集合的每个元素。以下示例中对 firstIndex(where:)
的调用必须遍历整个集合以找到与谓词匹配的元素:
let runner = "Marlies Gohr"
if let index = recordTimes.firstIndex(where: { $0.0 == runner }) {
let time = recordTimes[index].1
print("\(runner) set a 100m record of \(time) seconds.")
} else {
print("\(runner) couldn't be found in the records.")
}
// Prints "Marlies Gohr set a 100m record of 10.81 seconds."
键值对作为函数参数
当调用带有 KeyValuePairs
参数的函数时,您可以传递 Swift 字典文字而不会创建 Dictionary
。当文字中元素的顺序很重要时,此函数尤其重要。
例如,您可以创建一个包含 two-integer 元组列表的 IntPairs
结构,并使用接受 KeyValuePairs
实例的初始化程序。
struct IntPairs {
var elements: [(Int, Int)]
init(_ elements: KeyValuePairs<Int, Int>) {
self.elements = Array(elements)
}
}
当您准备好创建新的 IntPairs
实例时,使用字典文字作为 IntPairs
初始化程序的参数。 KeyValuePairs
实例保留传递的元素顺序。
let pairs = IntPairs([1: 2, 1: 1, 3: 4, 2: 1])
print(pairs.elements)
// Prints "[(1, 2), (1, 1), (3, 4), (2, 1)]"
可用版本
iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+
相关用法
- Swift KeyValuePairs flatMap(_:)用法及代码示例
- Swift KeyValuePairs split(maxSplits:omittingEmptySubsequences:whereSeparator:)用法及代码示例
- Swift KeyValuePairs suffix(_:)用法及代码示例
- Swift KeyValuePairs prefix(_:)用法及代码示例
- Swift KeyValuePairs first用法及代码示例
- Swift KeyValuePairs isEmpty用法及代码示例
- Swift KeyValuePairs last(where:)用法及代码示例
- Swift KeyValuePairs randomElement(using:)用法及代码示例
- Swift KeyValuePairs last用法及代码示例
- Swift KeyValuePairs allSatisfy(_:)用法及代码示例
- Swift KeyValuePairs firstIndex(where:)用法及代码示例
- Swift KeyValuePairs index(_:offsetBy:limitedBy:)用法及代码示例
- Swift KeyValuePairs filter(_:)用法及代码示例
- Swift KeyValuePairs sorted(by:)用法及代码示例
- Swift KeyValuePairs reduce(_:_:)用法及代码示例
- Swift KeyValuePairs contains(where:)用法及代码示例
- Swift KeyValuePairs shuffled()用法及代码示例
- Swift KeyValuePairs lastIndex(where:)用法及代码示例
- Swift KeyValuePairs randomElement()用法及代码示例
- Swift KeyValuePairs subscript(_:)用法及代码示例
- Swift KeyValuePairs min(by:)用法及代码示例
- Swift KeyValuePairs suffix(from:)用法及代码示例
- Swift KeyValuePairs shuffled(using:)用法及代码示例
- Swift KeyValuePairs reduce(into:_:)用法及代码示例
- Swift KeyValuePairs max(by:)用法及代码示例
注:本文由纯净天空筛选整理自apple.com大神的英文原创作品 KeyValuePairs。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。