如何解决如何轻松地将 Dictionary<K,V>.Subsequence 转换为 Dictionary<K,V>
[更新] 挖掘我发现的字典方法:
.split(whereSeparator: (key,value)) -> [Slice.Dictionary<K,V>]
返回由以下组成的子序列:
_startIndex,_endindex and _base (that contains the original Dict)
我是为了好玩而尝试的。使用结果来获得一个字典需要一个循环来从索引创建一个字典。
你知道一种轻松地将子序列转换为字典的方法吗?我们用子序列字符串做到了吗?:
String(subsequence)
解决方法
虽然 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,3: 3].filter { $0.key <= 2 }
相反,如果您想要两个分割部分,作为字典,您可以使用它,它依赖于相同的 uniqueKeysWithValues
扩展初始值设定项。
// [false: [2: 2,1: 1],true: [3: 3]]
Dictionary(grouping: [1: 1,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) }
)
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。