Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Mutate an Array in a Dictionary?

I've tried the following in a Playground:

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

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

println(d1)

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

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

like image 379
Joe Smith Avatar asked Dec 15 '22 15:12

Joe Smith


1 Answers

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"]!

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")

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.

Option1: Append directly to the array inside d1.

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

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.

like image 75
jfocht Avatar answered Jan 02 '23 21:01

jfocht