xx11dragon xx11dragon - 3 months ago 6
Swift Question

Array mutability append in Swift

The new array was set up in itself call append()

In Xcode 7.3.1, I get these results:

import Foundation

var data = [[10]]
var firstObject = data[0]

print(unsafeAddressOf(firstObject))
firstObject.append(30)
print(unsafeAddressOf(firstObject))
print("--------")
print(firstObject)
print(data)
print("--------")
data[0] = firstObject
print(data)

--output:--

0x000000015fdea8a0
0x000000015fdea930
--------
[10, 30]
[[10]]
--------
[[10, 30]]


I try change object in array, but I failed.

so,i need run
data[0] = firstObject
in
array.append()
every time ?

Answer

Using your code, yes you need.

Swift Array is value type unlike Foundation NSArray which is reference type.

The line

var firstObject = data[0]

creates a copy of the object at index 0 of data and assigns it to the variable.

The next line

firstObject.append(30)

appends 30 to firstObject but data remains unchanged.

To update data you need to assign firstObject back to index 0 of data

Comments