Johannes
Johannes

Reputation: 440

Array of arrays swift behaviour

So im messing around with swift arrays, and they seem to be quite missleading in some areas although most of the stuff was fixed in xcode 6.1

i wanna make an array of arrays but it need to store the references, not only the values. how can i store the references of the arrays so that updates will also take effect on the "outer array"?

var a1 = [1,2]

var allarrays = [[Int]]()

allarrays.append(a1)

a1.append(99)

allarrays

allarys still gives me me [[1,2]] here, instead of [[1,2,99]]

Upvotes: 1

Views: 106

Answers (1)

Antonio
Antonio

Reputation: 72750

Unfortunately (for your specific problem) swift array are value types, and as such they are always passed by value.

A workaround that might work (with inherent drawbacks) is to use NSMutableArray, which is a reference type (i.e. a class) instead:

var a1: NSMutableArray = [1,2]

var allarrays: NSMutableArray = NSMutableArray()

allarrays.addObject(a1)

a1.addObject(99)

allarrays // [[1, 2, 99]]

Upvotes: 1

Related Questions