如何追加到数组,它是在斯威夫特字典中的价值 [英] How to append to an array that is a value in a Swift dictionary

查看:144
本文介绍了如何追加到数组,它是在斯威夫特字典中的价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们假设我有一个接受字符串作为键和一个数组作为值的字典:

Let's assume I have a dictionary that accepts a string as the key and an array as value:

var d = [String: [Int]]()
d["k"] = [Int]()

现在我想追加()来是在阵列的 [K] 。我该怎么做呢?

Now I would like to append() to the array that is under the ["k"]. How do I do that?

[Int](d["k"]).append(1) // error
(d["k"] as [Int]).append(1) // error

我想这是一些真正的基本的,但我不出来......非常感谢!

I guess this is something really basic but I cannot figure it out... thanks a lot!

推荐答案

由于字典和数组都是结构类型,你不能修改到位数组,而是要提取并恢复它:

Because Dictionary and Array are both struct types, you can't modify the Array in place, but instead have to extract and restore it:

if var items = d["k"] {
    items.append(1)
    d["k"] = items
}
else {
    d["k"] = [1]
}

这篇关于如何追加到数组,它是在斯威夫特字典中的价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆