Manuel Manuel - 1 year ago 67
Swift Question

How to keep the reference to an array after manipulation?

How do I keep the reference to an array after an items is appended?

Updated code example, because the prior example didn't seem to be clear enough.

class ViewController: UIViewController {

var numbers = Numbers.singleton.numbers

override func viewDidLoad() {



print(numbers.count) // prints 0
print(Numbers.singleton.numbers.count) // prints 1

class Numbers {

static let singleton = Numbers()

var numbers: [Int]!

private init() {
numbers = []

func add(number: Int) {

Answer Source

Arrays in Swift don't have "references". They are structs, and a struct is a value type. Your (badly named) arrayRef is a separate copy, not a reference to self.array.

Moreover, there is no good reason to want to do what you (seem to) want to do. To have two simultaneous references to a mutable array would be unsafe, since the array can be changed behind your back. The Swift design is sensible; use it, don't subvert it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download