首页 > 解决方案 > 从 KeyValuePairs 初始化 Dictionary(uniqueKeysWithValues:)

问题描述

struct Data {
    let storage: [String: Int]
    
    init(_ pairs: KeyValuePairs<String, Int>) {
        storage = Dictionary(uniqueKeysWithValues: pairs)
    }
}

编译错误:

初始化程序 'init(uniqueKeysWithValues:)' 要求类型 'KeyValuePairs<String, Int>.Element' (又名 '(key: String, value: Int)')和 '(String, Int)' 是等价的

还有什么比使用 KeyValuePairs 初始化 Dictionary(uniqueKeysWithValues:) 更自然的事情!简直可笑,不可能直截了当!
requires '(key: String, value: Int)' and '(String, Int)' be equivalent他们是等价的!

标签: swiftdictionaryswift5

解决方案


这是因为KeyValuePairs.Element有标签。

type(of: (key: "", value: 0)) == type(of: ("", 0)) // false

您需要另一个重载或只是就地删除标签。

public 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.
  @inlinable init<Elements: Sequence>(uniqueKeysWithValues keysAndValues: Elements)
  where Elements.Element == Element {
    self.init(
      uniqueKeysWithValues: keysAndValues.map { ($0, $1) }
    )
  }
}
XCTAssertEqual(
  Dictionary(
    uniqueKeysWithValues: ["": "", "‍♀️&quot;: "‍♂️&quot;] as KeyValuePairs
  ),
  .init(
    uniqueKeysWithValues: [("", ""), ("‍♀️&quot;, "‍♂️&quot;)]
  )
)

推荐阅读