How to get a pointer (instead of a copy) to an array in Swift?
Not a ‘pure’ Swift solution, but using NSArray will give you the reference semantics you desire.
NSArray
is toll-free bridgeable to Array
, so you can use plain as
instead of as!
var numbers = [1, 2, 3, 4, 5]
var numbersCopy = numbers as NSArray
numbers[0] = 100
print(numbers)
[100, 2, 3, 4, 5]
print(numbersCopy as Array)
[1, 2, 3, 4, 5]
If you are modifying the 'copy' you will need to use a NSMutableArray
.
Edit:
oops
I think I was confused by the naming of your variable numbersCopy
. I see now that you want the 'copy' to share the same value as the original. By capturing the variable numbers
in a block, and executing that block later, you can get the current value of numbers
, and you don't need to use NSArray at all.
var numbers = [1, 2, 3, 4, 5]
var numbersCopy = {numbers}
numbers[0] = 100
print(numbers)
[100, 2, 3, 4, 5]
print(numbersCopy())
[100, 2, 3, 4, 5]