Search code examples
arraysswiftmutable

Variables sharing the same array instance - Javascript like array


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.


Solution

  • 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"