如何在Swift中将存储在常量中的dictionary元素直接添加到dictionary literal中



我正在将一个特定的dictionary元素添加到多个dictionary中,因此我想将这个元素存储在一个常量中,以便可以轻松地重用它。

我喜欢做这样的事情:

let reusableElement: Dictionary<String, String>.Element = ("reusableKey", "reusableValue")
let dictUsingTheReusableElement: [String: Any] = ["name": "john",
"age": 15,
"legend": true,
reusableElement]

这导致以下错误Expected ':' in dictionary literal

有没有一种方法可以直接将元素插入字典中?或者只有这样做才能添加这个:

let dictUsingTheReusableElement: [String: Any] = ["name": "john",
"age": 15,
"legend": true,
reusableElement.0: reusableElement.1]

我想字典文本的困难部分是,如果元素的键已经在文本中,它会怎么做。你可以看到你是否实现了这样的东西:

let element: Dictionary<String, String>.Element = ("rK", "rV")
extension Dictionary where Key == String, Value == Any {
func with(_ element: Element) -> Self {
merging([element.0: element.1], uniquingKeysWith: { a, _ in a})
}
}

let dictUsingTheReusableElement: [String: Any] = ["name": "john",
"age": 15,
"legend": true]
.with(element)

您需要指定如何处理与uniquingKeys(with:的冲突

事实上,如果你做

let reusableElement: Dictionary<String, String>.Element = ("name", "foo")
let dictUsingTheReusableElement: [String: Any] = ["name": "john",
"age": 15,
"legend": true,
reusableElement.0: reusableElement.1]

您将遇到运行时问题(Swift/Dictionary.Swift:826:致命错误:Dictionary literal包含重复的键(,所以这可能就是为什么它不是一件事。

最新更新