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 ?

2
  • 1
    Why are you printing memory address. you can append data directly by data[0].append(30) Commented Aug 9, 2016 at 9:02
  • 2
    Note that unsafeAddressOf is useless with value types (such as firstObject which is an Array), see for example stackoverflow.com/questions/32638879/…. Commented Aug 9, 2016 at 9:02

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.