jignesh Vadadoriya
jignesh Vadadoriya

Reputation: 3310

Swift Array behaviour

I have created one class which look like this

class IntegerReference {
    var value = 10
}

Then i have allocate array firstIntegers which contains IntegerReference And anther array secondIntegersis just assign reference of firstIntegers

var firstIntegers = [IntegerReference(), IntegerReference()]
var secondIntegers = firstIntegers

Now i want to change the value of firstIntegers array

firstIntegers[0].value = 100
print(firstIntegers[0].value) //100  it is ok..
print(secondIntegers[0].value) //100 it is ok..

But when i want to modify firstIntegers array it will not affect on secondIntegers array

firstIntegers[0] = IntegerReference()
print(firstIntegers[0].value)   //10    it is ok..
print(secondIntegers[0].value) // 100   Why 100? it should be 10 or Not?

Upvotes: 0

Views: 63

Answers (1)

Eendje
Eendje

Reputation: 8883

The reason why the value in secondIntegers changes when you change the value in firstIntegers is because IntegerReference is a class (example 1).

The moment you replaced the instance in firstIntegers, a new instance of IntegerReference is placed in firstIntegers. But the old instance with the value of 100 is still inside secondIntegers, which is why it still prints 100 when accessed (example 2).

To show you what I meant I've created a few examples including the address of the instances.

Data:

class Foo { 
    var value = 10 
}

var array1 = [Foo(), Foo()]
var array2 = array1

Example 1:

array1[0].value = 100

print("address:", getAddress(array1[0]), "value:", array1[0].value)
print("address:", getAddress(array2[0]), "value:", array2[0].value)

Output:

address: 0x000060000002d820 value: 100
address: 0x000060000002d820 value: 100

Example 2:

array1[0] = Foo()

print("address:", getAddress(array1[0]), "value:", array1[0].value)
print("address:", getAddress(array2[0]), "value:", array2[0].value)

Output:

address: 0x000060800002c120 value: 10
address: 0x000060000002d820 value: 100

Edit:

In case you wonder how I got the address:

func getAddress(_ object: AnyObject) -> UnsafeMutableRawPointer {
    return Unmanaged.passUnretained(object).toOpaque()
}

Upvotes: 2

Related Questions