Manuel Manuel - 6 months ago 9
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)

Numbers.singleton.add(1)

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) {
numbers.append(number)
}
}

Answer

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.

Comments