如何在字典中对数组进行变异? [英] How to Mutate an Array in a Dictionary?

查看:70
本文介绍了如何在字典中对数组进行变异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在操场上尝试了以下方法:

I've tried the following in a Playground:

var d1 = [String: [String]]()
d1["a"] = [String]()

var a1 = d1["a"]!
a1.append("s1")

println(d1)

输出为:[a: []]
我一直希望:[a: ["s1"]]

The output is: [a: []]
I was hoping for: [a: ["s1"]]

在字典中对数组进行突变的正确方法是什么?

What would be the right way to mutate an array in a dictionary?

推荐答案

迅速地,当结构被分配给新变量时,它们将按值复制.因此,当您将a1分配给字典中的值时,它实际上会创建一个副本.这是我正在谈论的行:

In swift, structures are copied by value when they get assigned to a new variable. So, when you assign a1 to the value in the dictionary it actually creates a copy. Here's the line I'm talking about:

var a1 = d1["a"]!

该行被调用后,实际上有两个列表:d1["a"]引用的列表和a1引用的列表.因此,当您调用以下行时,只有第二个列表会被修改:

Once that line gets called, there are actually two lists: the list referred to by d1["a"] and the list referred to by a1. So, only the second list gets modified when you call the following line:

a1.append("s1")

打印时,您正在打印第一个列表(存储为词典d1中的键"a").这是您可以用来获得预期结果的两种解决方案.

When you do a print, you're printing the first list (stored as the key "a" in dictionary d1). Here are two solutions that you could use to get the expected result.

选项1:直接附加到d1内部的数组.

Option1: Append directly to the array inside d1.

var d1 = [String : [String]]()
d1["a"] = [String]()
d1["a"]?.append("s1")
println(d1)

选项2:附加到复制的数组,并将该值分配给d1中的"a".

Option 2: Append to a copied array and assign that value to "a" in d1.

var d1 = [String : [String]]()
d1["a"] = [String]()
var a1 = d1["a"]!
a1.append("s1")
d1["a"] = a1
println(d1)

第一种解决方案性能更高,因为它不会创建列表的临时副本.

The first solution is more performant, since it doesn't create a temporary copy of the list.

这篇关于如何在字典中对数组进行变异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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