【问题标题】:How to a convert a Dictionary Slice to a Dictionary in Swift如何在 Swift 中将字典切片转换为字典
【发布时间】:2016-11-02 09:41:12
【问题描述】:

我正在尝试将 myDictionary.dropFirst() 转换为缺少一个键的新字典(我不在乎哪个键)。 dropFirst() 返回一个切片。我想要一个与myDictionary 相同类型的新字典。

您可以将 Array 切片转换为类似 let array = Array(slice) 的数组。字典的等价物是什么?如果我尝试 Dictionary(slice) 我得到编译错误Argument labels '(_:)' do not match any available overloads

非常感谢。

【问题讨论】:

    标签: swift slice


    【解决方案1】:
    Dictionary(uniqueKeysWithValues: [1: 1, 2: 2, 3: 3].dropFirst())
    

    请参阅我的Note,了解为什么需要此重载才能进行编译。

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

    【讨论】:

      【解决方案2】:

      没有像ArraySlice 这样的DictionarySlice。相反,dropFirst() 返回一个 Slice&lt;Dictionary&gt;,它不像 Dictionary 那样支持键下标。但是,您可以像使用 Dictionary 一样使用键值对循环遍历 Slice&lt;Dictionary&gt;

      let dictionary = ["a": 1, "b": 2, "c": 3]
      
      var smallerDictionary: [String: Int] = [:]
      
      for (key, value) in dictionary.dropFirst() {
          smallerDictionary[key] = value
      }
      
      print(smallerDictionary) // ["a": 1, "c": 3]
      

      一个扩展会让这更优雅一点:

      extension Dictionary {
      
          init(_ slice: Slice<Dictionary>) {
              self = [:]
      
              for (key, value) in slice {
                  self[key] = value
              }
          }
      
      }
      
      let dictionary = ["a": 1, "b": 2, "c": 3]
      let smallerDictionary = Dictionary(dictionary.dropFirst())
      print(smallerDictionary) // ["a": 1, "c": 3]
      

      不过,我真的不建议这样做,因为

      • 您不知道将删除哪个键值对,并且
      • 它也不是真正随机的。

      但如果你真的想这样做,现在你知道该怎么做了。

      【讨论】:

        猜你喜欢
        • 2015-06-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-18
        • 2015-11-05
        相关资源
        最近更新 更多