swift - 从 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
他们是等价的!
解决方案
这是因为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: ["": "", "♀️": "♂️"] as KeyValuePairs
),
.init(
uniqueKeysWithValues: [("", ""), ("♀️", "♂️")]
)
)
推荐阅读
- javascript - 如何使隐藏的 div 出现在 Javascript 中的按钮单击上
- ios - WKWebView 在 html 中打开 src
- cordova - 执行从 InAppBrowser 的 executeScript 调用的打字稿函数
- swift - Array 上的扩展,其中 Element 是通用的,未编译
- webpack - Autoprefixer 不使用带有 cssnano 和 postcss 的“grid: autoplace”
- r - 根据条件从另一列插入值
- json - 输入不是有效的 Base-64 字符串错误,我的 JSON 使用双引号而不是单引号
- database - Elasticsearch如何设置fielddata:所有文本字段都为true
- python - ImportError:DLL 加载失败:找不到网络名称
- powerbi - 计算 Power BI 中的贡献