【发布时间】:2020-08-29 09:11:36
【问题描述】:
struct Data {
let storage: [String: Int]
init(_ pairs: KeyValuePairs<String, Int>) {
storage = Dictionary(uniqueKeysWithValues: pairs)
}
}
编译错误:
Initializer 'init(uniqueKeysWithValues:)' 需要类型 'KeyValuePairs
.Element' (又名 '(key: String, value: Int)') 和 '(String, Int)' 等价
还有什么比使用 KeyValuePairs 初始化 Dictionary(uniqueKeysWithValues:) 更自然的方法!简直可笑,不能直截了当!requires '(key: String, value: Int)' and '(String, Int)' be equivalent他们是等价的!p>
【问题讨论】:
-
storage = Dictionary(uniqueKeysWithValues: Array(pairs))应该可以解决问题。KeyValuePair不是序列,毕竟是public init<S>(uniqueKeysWithValues keysAndValues: S) where S : Sequence, S.Element == (Key, Value)。 -
@Larme 是的,这行得通。我将深入研究文档以理解您的解释,但您的代码可以按预期编译和工作。你能发个帖子吗,我可以把它作为答案:)
-
@Larme 类型不是
KeyValuePair,是KeysValue*PAIRS*。
标签: swift dictionary swift5