this is probably a very basic/stupid question: how do I get a reference to a collection in Swift, such that a change to that reference affects the original and vice versa? So if for instance I have the following code:
var a1 = [Int]()
var a2 = a1
a1.append(1)
print(a2)
Can I get a "reference" (or whatever name it would have in Swift) to a1
such that when I change a1
, a2
reflects the same change, and it ends up displaying "[1]" instead of "[]"?
I guess this has to do with collections being primary types, and thus not behaving like other objects, but then I'm at a loss as to how I can play around with collections without them being duplicated all the time.
More specifically, when working with a Dictionary<String, Dictionary<String, Int>>
, what's the best way to update the contents of the nested Dictionary
while minimizing the number of lookups? The following approach used to work in Java but I guess it's different with Swift:
var dict = Dictionary<String, Dictionary<String, Int>>()
var d = dict["a"]
if d == nil {
d = Dictionary()
dict["a"] = d
}
d!["b"] = 1
print("\(dict["a"]!["b"])")
prints "nil"
(Note: if possible, I'd like to avoid multiple dict["a"]!["b"]
lookups)
Thanks!