0

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 ?

xx11dragon
  • 166
  • 1
  • 10
  • 1
    Why are you printing memory address. you can append data directly by `data[0].append(30)` – Khundragpan Aug 09 '16 at 09:02
  • 2
    Note that `unsafeAddressOf` is *useless* with value types (such as `firstObject` which is an `Array`), see for example http://stackoverflow.com/questions/32638879/swift-strings-and-memory-addresses. – Martin R Aug 09 '16 at 09:02

1 Answers1

1

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

vadian
  • 274,689
  • 30
  • 353
  • 361