Reputation: 97
Suppose that some potentially large block of code needs to work with an array which is either array A or array B. Instead of writing
switch (x) {
case a:
arrayA.append(X)
case b:
arrayB.append(X)
}
I would like to write something like the following C++ code:
auto& arr = (x == a ? arrayA : arrayB);
arr.push_back(X);
Of course in real life the cases aren't that simple, but I hope you get the point: I would like to set up the reference just once and after that not care about which array I am working with.
Upvotes: 1
Views: 111
Reputation: 72760
I am not aware of any way to obtain an array pointer - the only case where a reference is passed around is to a function parameter, using the inout
modifier.
However closures are very flexible and usable in several ways - I think this is one of those cases. The idea is to create 2 closures, the 1st appending to arrayA
, the 2nd to arrayB
, then store the closure you want to use in a variable, and use it:
typealias PushToArrayClosure = (value: Int) -> Void
var arrayA = [1, 2, 3]
var arrayB = [4, 5, 6]
let condition = false
let pushA = { (value: Int) in
arrayA.append(value)
}
let pushB = { (value: Int) in
arrayB.append(value)
}
let pushToArray: PushToArrayClosure = condition ? pushA : pushB
pushToArray(value: 7)
arrayA // contains [1, 2, 3]
arrayB // contains [4, 5, 6, 7]
Upvotes: 1