【问题标题】:How to easlily convert a Dictionary<K,V>.Subsequence to Dictionary<K,V>如何轻松地将 Dictionary<K,V>.Subsequence 转换为 Dictionary<K,V>
【发布时间】:2021-04-26 23:33:31
【问题描述】:

[更新] 挖掘我找到的字典方法:

.split(whereSeparator: (key, value)) -> [Slice.Dictionary<K,V>]

返回由以下组成的子序列:

_startIndex, _endIndex and _base (that contains the original Dict)

我尝试过是为了好玩。使用结果来获取字典需要一个循环来从索引创建字典。

您知道一种将 Subsequence 轻松转换为 Dict 的方法吗?我们是否使用 subsequence String 来做到这一点?:

String(subsequence)

【问题讨论】:

  • 字典是无序的,那么在给定的条目上如何进行拆分呢?每次执行都可能不同。
  • 拆分字典真的没有意义。你想用它做什么?
  • 在我看来使用过滤器可能更好
  • 会更容易使用reduced(into:_:) 而不是奇怪的拆分等。

标签: swift


【解决方案1】:

虽然 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) }
    )
  }
}

【讨论】:

  • 谢谢@Jessy。所以首先是 .flatMap { $0 } 然后是 Dictionary 的扩展,以支持带有标签元组的 init。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-26
  • 2010-09-21
相关资源
最近更新 更多