问题
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?
回答1:
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.
回答2:
Extending the excellent answer of @jfocht here is
Option 3: Append within function where array is passed by reference
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]]
Added some sugar in the sense that it actually creates a new array if given a dictionary key with no arrays attached currently.
回答3:
Swift Array and Dictionary are not an objects like NSArray and NSDictionary. They are struct. So by doing var a1 = d1["a"] would be like doing var a = point.x and then change a but of course the point.x will not change.
So by doing this instead:
d1["a"] = []
d1["a"]!.append("")
Would be like doing point.x = 10
回答4:
you need to set a new value for key "a" inside your dictionary.
Which means:
d1["a"] = a1
来源:https://stackoverflow.com/questions/29189955/how-to-mutate-an-array-in-a-dictionary