我有一本看起来像这样的字典:
var dict = [String: [String]]()
我希望能够为单个键添加多个数组。这很好用:
dict["hello"] = ["item 1"]
但是当我分配一个新数组时,之前的值显然被覆盖了——我们想避免这种情况:
dict["hello"] = ["item 2"] // overwrites item 1 – how to avoid overwriting?
所以我尝试使用 append
方法,但这返回 nil:
dict["hello"]?.append("test") // does nothing? output: ()
如何在 Swift 中将字符串附加到某个键的数组(值)?
最佳答案
首先……
...你真的不想要这个
I want to be able to add multiple arrays for a single key.
相反,我认为你想要...
... to add a string to the array associated to a given string
例子
换句话说,你想从这里开始
["hello":["item 1"]]
对此
["hello":["item 1", "item 2"]]]
那么,怎么做呢?
让我们从你的字典开始
var dict = [String: [String]]()
dict["hello"] = ["item 1"]
现在您需要提取与hello
键关联的数组
var list = dict["hello"] ?? []
添加一个字符串
list.append("item 2")
最后将更新后的数组添加回字典
dict["hello"] = list
就是这样
关于arrays - 字典 [字符串 : [String]] in Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44609216/