1

In Javascript, when you do that :

var a = [1, 2];

var b = a;

b.push(3);

console.log(a); //Print [1, 2, 3]

a and b share the same array instance. I am looking for a way to achieve this in Swift

Here is my Swift code :

var array1 = [[1], [2], [3]];

var array2 = array1[0];

array2.append(0);

print(array1);
//print [[1], [2], [3]]
//I want [[1, 0], [2], [3]]

array1[0] & array2 are two different instances ... I'd like two variables (with different names) pointing to the same instance of an array.

3

1 Answer 1

2

You have to wrap a value type into a reference type ie class.

class wrapper {
    var array = [1,2]
}

var a = wrapper()

var b = a

b.array.append(3)

print(a.array) // [1,2,3]

Reading here You can also use NSMutableArray

var c : NSMutableArray = [1,2]


var d = c

d.insert(3, at: 2)

print(c) //"(\n    1,\n    2,\n    3\n)\n"
Sign up to request clarification or add additional context in comments.

7 Comments

I'm not sure as to which is faster/better, but I think if you only want an array, then using NSMutableArray is preferred, but if you want a model, ie something that also stores an array and needs to be persisted then perhaps wrapping it inside a class is a better choice.
A wrapper type is far better, as you don't throw away the type information of what the elements are, unlike NSMutableArray (and you don't needlessly bridge the elements over to Obj-C). You can make the wrapper generic in order to store different types of arrays, such as shown in Qbyte's answer here.
@Hamish Faster because no bridging? OK. What do you mean when you say "don't throw away the type information" you mean generics?
I mean that in your example wrapper contains an array property of type [Int], therefore you know that it contains only Ints. NSMutableArray on the other hand just contains heterogeneous NSObjects (bridged back to Swift as Any) – the elements could be a mix of NSNumbers, UIViews and UIColors for all we know. Therefore you'll have to do some type-casting before you can do anything useful with them.
Thanks. I understand the concept now. "therefore you know that it contains only Ints". So in my answer, I am throwing the type information ie I'm saying it's of type Int. I feel like my jargon is different than yours. Why did you say " as you don't throw away"
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.