虽然 here 已经回答了您的问题,但对于 split 来说还不够,因为它涉及多个切片,因此还需要平面映射或等价物。
Dictionary(
uniqueKeysWithValues:
[1: 1, 2: 2, 3: 3]
.split { $0.key > 2 } // filters out (key: 3, value: 3)
.flatMap { $0 }
)
但是,我认为它实际上并没有用,因为使用 filter 和反转条件会产生相同的结果。
[1: 1, 2: 2, 3: 3].filter { $0.key <= 2 }
如果您希望将两个拆分部分都用作字典,则可以使用它,它依赖于相同的 uniqueKeysWithValues 扩展初始化程序。
// [false: [2: 2, 1: 1], true: [3: 3]]
Dictionary(grouping: [1: 1, 2: 2, 3: 3]) { $0.key > 2 }
.mapValues(Dictionary.init)
extension Dictionary {
/// Creates a new dictionary from the key-value pairs in the given sequence.
///
/// - Parameter keysAndValues: A sequence of key-value pairs to use for
/// the new dictionary. Every key in `keysAndValues` must be unique.
/// - Returns: A new dictionary initialized with the elements of `keysAndValues`.
/// - Precondition: The sequence must not have duplicate keys.
/// - Note: Differs from the initializer in the standard library, which doesn't allow labeled tuple elements.
/// This can't support *all* labels, but it does support `(key:value:)` specifically,
/// which `Dictionary` and `KeyValuePairs` use for their elements.
init<Elements: Sequence>(uniqueKeysWithValues keysAndValues: Elements)
where Elements.Element == Element {
self.init(
uniqueKeysWithValues: keysAndValues.map { ($0.key, $0.value) }
)
}
}