How to mutate an array in a dictionary?

I tried the following on the playground:

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

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

println(d1)

Conclusion: [a: []]
I was hoping:[a: ["s1"]]

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

+4
source share
4 answers

In fast structures, they are copied by value when they are bound to a new variable. So, when you assign a a1value in a dictionary, it actually creates a copy. Here is the line I'm talking about:

var a1 = d1["a"]!

After calling this line, there are actually two lists: the list that is referenced d1["a"], and the list that is referenced a1. Thus, only the second list changes when you call the following line:

a1.append("s1")

, ( "a" d1). , .

Option1: d1.

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

2: "a" d1.

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

, .

+7

Swift Array Dictionary NSArray NSDictionary. struct. , var a1 = d1["a"], var a = point.x, a, , , point.x .

, :

d1["a"] = []
d1["a"]!.append("")

point.x = 10

+1

@jfocht

3: ,

func myAdd(s : String, inout arr : [String]?) {
    if arr == nil
    {
        arr = [String]()
    }
    arr?.append(s)
}

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

myAdd("s1", &d1["a"])
myAdd("s2", &d1["b"])

println(d1) // [ b: [s2], a: [s1]]

, , .

+1
source

you need to set a new value for the key "a"inside your dictionary. It means:

d1["a"] = a1

0
source

All Articles