【问题标题】:How to add another dictionary entry to an existing dictionary to form a new dictionary (i.e. not append)如何将另一个字典条目添加到现有字典以形成新字典(即不附加)
【发布时间】:2020-11-20 00:49:06
【问题描述】:

我想在 swift 中向字典中添加另一个字典条目,例如

let a: [String: Any] = ["Test": 1, "good":false]
let b = a + ["hello": "there"]
print(b)

(抱歉,+ 在这里看起来很疯狂,因为这就是 Kotlin 实现这一点的方式。我对 Kotlin 比对 Swift 更熟悉。)

但我收到错误Binary operator '+' cannot be applied to two '[String : Any]' operands

我也不能使用updateValue

let a: [String: Any] = ["Test": 1, "good":false]
let b = a.updateValue("hello": "there")
print(b)

会报错Cannot use mutating member on immutable value: 'a' is a 'let' constant

我可以按照 https://stackoverflow.com/a/26728685/3286489 的提议通过扩展函数来实现这一点

但它看起来有点矫枉过正。

let b = a.merge(dict: ["hello": "there"])
print(b)


extension Dictionary {
    func merge(dict: Dictionary<Key,Value>) -> Dictionary<Key,Value> {
        var mutableCopy = self
        for (key, value) in dict {
            // If both dictionaries have a value for same key, the value of the other dictionary is used.
            mutableCopy[key] = value
        }
        return mutableCopy
    }
}

是否有一个简单的运算符,我可以在其中添加另一个条目以用于新字典?

注意:我不是指 How to append elements into a dictionary in Swift? 中的追加,因为我收到了一个不可变字典 let,我需要向其中添加另一个条目。

【问题讨论】:

    标签: swift dictionary


    【解决方案1】:

    Dictionary 上有一个内置的 merging(_:uniquingKeysWith:) 函数,可以完全满足您的需求。

    let dictionary = [1:1]
    let otherDictionary = [1:2, 2:3]
    // This will take the values from `otherDictionary` if the same key exists in both
    // You can use `$0` if you want to take the value from `dictionary` instead
    let mergedDict = dictionary.merging(otherDictionary, uniquingKeysWith: { $1 })
    

    如果需要,您可以轻松地为使用上述函数的Dictionary 定义一个+ 运算符。

    extension Dictionary {
        static func + (lhs: Self, rhs: Self) -> Self {
            lhs.merging(rhs, uniquingKeysWith: { $1 })
        }
    }
    
    let addedDict = dictionary + otherDictionary
    

    【讨论】:

    • 谢谢。我想我可以使用它。不过它看起来确实有点太长了,因为我真的只有一个条目要添加,而不是真正的字典。有没有更短的方法?在 Kotlin(我更熟悉 Android)中,我可以使用 + 运算符来生成新地图(即 Swift 中的字典)。如果没有,那我就用这个。
    • @Elye 对此没有内置运算符,因为如果两个字典中都存在键,则没有通用方法来分配应分配的值。但是,您可以轻松实现自己的 + 运算符,查看我更新的答案
    • 不错,喜欢+ 自定义运算符。谢谢!!
    • 我只是好奇为什么我的问题被否决了。我进行了研究,并利用我的 Kotlin 知识来探索解决方案。事实上,没有像 Kotlin 那样的直接解决方案(这误导我认为那里有这样的解决方案)。请原谅我对 Swift 语言的幼稚和无知。
    • @Elye 不确定,我不是对你的问题投反对票的人,对我来说这似乎是一个高质量的问题
    猜你喜欢
    • 1970-01-01
    • 2018-07-27
    • 2021-05-17
    • 2020-05-21
    • 2023-02-24
    • 2020-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多