初始化器
init(_:
init(_:uniquingKeysWith:)
从给定序列中的键值对创建一个新字典,使用组合闭包来确定任何重复键的值。
声明
init<S>(
_ keysAndValues: S,
uniquingKeysWith combine: (Value, Value) throws -> Value) rethrows where S : Sequence, S.Element == (Key, Value
)
参数
keysAndValues
用于新字典的键值对序列。
combine
使用遇到的任何重复键的值调用的闭包。闭包返回最终字典所需的值。
详述
当您有一系列可能具有重复键的键值元组时,您可以使用此初始化程序来创建字典。在构建字典时,初始化程序使用任何重复键的当前值和新值调用 combine
闭包。将闭包作为combine
传递,该闭包返回要在结果字典中使用的值:闭包可以在两个值之间进行选择,将它们组合以产生新值,甚至抛出错误。
以下示例显示如何为任何重复键选择第一个和最后一个值:
let pairsWithDuplicateKeys = [("a", 1), ("b", 2), ("a", 3), ("b", 4)]
let firstValues = Dictionary(pairsWithDuplicateKeys,
uniquingKeysWith: { (first, _) in first })
// ["b": 2, "a": 1]
let lastValues = Dictionary(pairsWithDuplicateKeys,
uniquingKeysWith: { (_, last) in last })
// ["b": 4, "a": 3]
可用版本
iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+
相关用法
- Swift Dictionary init(uniqueKeysWithValues:)用法及代码示例
- Swift Dictionary init(grouping:by:)用法及代码示例
- Swift Dictionary init(dictionaryLiteral:)用法及代码示例
- Swift Dictionary index(forKey:)用法及代码示例
- Swift Dictionary indices用法及代码示例
- Swift Dictionary index(_:offsetBy:)用法及代码示例
- Swift Dictionary index(_:offsetBy:limitedBy:)用法及代码示例
- Swift Dictionary isEmpty用法及代码示例
- Swift Dictionary allSatisfy(_:)用法及代码示例
- Swift Dictionary values用法及代码示例
- Swift Dictionary dropFirst(_:)用法及代码示例
- Swift Dictionary firstIndex(where:)用法及代码示例
- Swift Dictionary first(where:)用法及代码示例
- Swift Dictionary merge(_:uniquingKeysWith:)用法及代码示例
- Swift Dictionary subscript(_:default:)用法及代码示例
- Swift Dictionary reduce(_:_:)用法及代码示例
- Swift Dictionary suffix(from:)用法及代码示例
- Swift Dictionary subscript(_:)用法及代码示例
- Swift Dictionary makeIterator()用法及代码示例
- Swift Dictionary randomElement()用法及代码示例
- Swift Dictionary dropLast(_:)用法及代码示例
- Swift Dictionary min(by:)用法及代码示例
- Swift Dictionary max(by:)用法及代码示例
- Swift Dictionary updateValue(_:forKey:)用法及代码示例
- Swift Dictionary removeValue(forKey:)用法及代码示例
注:本文由纯净天空筛选整理自apple.com大神的英文原创作品 Dictionary init(_:uniquingKeysWith:)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。