显然我最初在阅读这个问题时很模糊,所以有了更新的(并且希望是准确的)理解,我将通过给出我认为 OP 想要做的具体(和可编译的)代码来重新表达这个问题,然后给出我的解决方案。
我已经重命名了一些东西,使其更具体并在代码中表达它们的角色。给定这样的代码:
var sourceArray1 = [1, 2, 3, 4]
var sourceArray2 = [5, 6, 7, 8]
func someFunc(_ someArray: inout [Int]) {
someArray.indices.forEach { someArray[$0] = 0 }
}
let someCase = true // just for the sake of compiling a concrete case
//usage code
var arrayProxy: [Int]
if someCase {
arrayProxy = sourceArray1
// Some additional code that may or may not involve arrayProxy
} else {
arrayProxy = sourceArray2
// Some additional code that may or may not involve arrayProxy
}
someFunc(&arrayProxy)
print("sourceArray1 = \(sourceArray1)")
print("sourceArray2 = \(sourceArray2)")
实际输出是
sourceArray1 = [1, 2, 3, 4]
sourceArray2 = [5, 6, 7, 8]
但所需的输出是
sourceArray1 = [0, 0, 0, 0]
sourceArray2 = [5, 6, 7, 8]
因此,该语句选择的任何源数组都是if
要更改的数组,并且arrayProxy
尽管它可能在以后的代码中使用,但对于此处所需的效果而言并不重要。
我不认为指针是正确的解决方案。我认为轻微的设计修改会更好。想要改变一个源数组,那么为什么不这样做呢?我的解决方案是这样的:
var sourceArray1 = [1, 2, 3, 4]
var sourceArray2 = [5, 6, 7, 8]
func someFunc(_ someArray: inout [Int]) {
someArray.indices.forEach { someArray[$0] = 0 }
}
func caseTrue(_ someArray: inout [Int]) -> [Int]
{
// The additional code from the if statement's `true` branch
someFunc(&someArray)
return someArray
}
func caseFalse(_ someArray: inout [Int]) -> [Int] {
// The additional code from the if statement's `false` branch
someFunc(&someArray)
return someArray
}
let someCase = true // just for the sake of compiling a concrete case
//usage code - assuming arrayProxy is still needed for something in later code
let arrayProxy = someCase ? caseTrue(&sourceArray1) : caseFalse(&sourceArray2)
print("sourceArray1 = \(sourceArray1)")
print("sourceArray2 = \(sourceArray2)")
caseTrue
并且caseFalse
可以是嵌套在包含 的方法内的本地函数,if
因此它们不会污染当前上下文之外的代码。
class AClass
{
var sourceArray1 = [1, 2, 3, 4]
var sourceArray2 = [5, 6, 7, 8]
init() { }
func someFunc(_ someArray: inout [Int]) {
someArray.indices.forEach { someArray[$0] = 0 }
}
func aMethod()
{
func caseTrue(_ someArray: inout [Int]) -> [Int]
{
// The additional code from the if statement's `true` branch
someFunc(&someArray)
return someArray
}
func caseFalse(_ someArray: inout [Int]) -> [Int] {
// The additional code from the if statement's `false` branch
someFunc(&someArray)
return someArray
}
let someCase = true // just for the sake of compiling a concrete case
//usage code - assuming arrayProxy is still needed for something in later code
let arrayProxy = someCase ? caseTrue(&sourceArray1) : caseFalse(&sourceArray2)
print("sourceArray1 = \(sourceArray1)")
print("sourceArray2 = \(sourceArray2)")
}
}
caseTrue
如果和的主体caseFalse
依赖于 中的局部变量aMethod
,那不是问题。局部函数就像闭包一样从周围的上下文中捕获变量(事实上,在 Swift 中它们基本上只是命名为闭包)。所以在你需要调用它们之前声明这些函数,这意味着它们上面可能有一些代码在aMethod
.