Update Swift arrays are too weird. I think it's more reliable to just use NSMutableArrays instead if this behaviour is needed.
I understand that Swift typically passes array by value rather than by reference, but I need to be able to pass a reference in code like this:
var arr1 = [1, 2, 4]
var arr2 = [4, 6, 3]
var result = pickOne() ? arr1 : arr2
result[2] = 7
// one of these should be updated, currently they are just as initialized
println(arr1)
println(arr2)
I want to dynamically select one of the two arrays, and make changes to that array. Both arrays are the same size and content type, and I would only be changing elements, not appending or removing. How can I achieve this?
Edit: Is the answer to just use NSMutableArray instead?
Just to clarify: pickOne() is a function that I already have, and based on results of that function I want to modify either first or second array. So I don't need help deciding which to choose. I need help figuring out how to make modifications (and there will be several) to that desired array without having to check which array to use for every modification.
I could do something like this:
if pickOne() {
// work on arr1
// ...
} else {
// work on arr2
// ...
}
// do some other work
// ...
if pickOne() {
// work more on arr1
// ...
} else {
// work more on arr2
// ...
}
// do yet another set of things
// ...
if pickOne() {
// work again on arr1
// ...
} else {
// work again on arr2
// ...
}
But this gets old fast.
Edit So far I have reached some progress here
var result = pickOne() ? UnsafeMutableBufferPointer(start: &arr1, count: arr1.count) : UnsafeMutableBufferPointer(start: &arr2, count: arr2.count)
I don't care too much that the reference is unowned because the arrays are actually strongly held properties of self so should not really get released unexpectedly, but the usage sure looks ugly. It's pretty disappointing that you need to call functions with scary names Unsafe when trying to do something so primitive.
inoutkeyword and use of additional functions, which gets quite bulky, and so far I've had no luck actually making it work for this use case.UnsafeMutableBufferPointeris doing the trick, but damn, it's ugly.