arrays - 字典 [字符串 : [String]] in Swift

标签 arrays swift dictionary value-type

我有一本看起来像这样的字典:

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/

相关文章:

javascript - 当它在 javascript 中变为 null 时,数组元素会变成什么?

c# - 读取字节数组 Textbox -> byte[]

php - 如何将api结果添加到mysql

ios - 如何在 Swift 中为 URL 编码大型数据对象?

swift - 如何从错误对象中识别错误类型

c++ - 按值排序 std::map

python - 如何使用 np.where() 创建特定行的新数组?

swift - 使用计时器在后台刷新应用程序

python - 按 x、y 和多个 z 存储点

iphone - 添加小数点后的字典上的ios双引号