如果为两个参数传递相同的变量会出错。 谁能解释为什么我们不能在输入参数函数中传递相同的变量,而我们可以在普通函数中传递
func swapTwoInts(a: inout Int, b: inout Int) {
print(a)
print(b)
}
var a = 12
swapTwoInts(a: &a, b: &a)
最佳答案
来自 Apple Documentation :
Within a function, don’t access a value that was passed as an in-out argument, even if the original value is available in the current scope. Accessing the original is a simultaneous access of the value, which violates Swift’s memory exclusivity guarantee. For the same reason, you can’t pass the same value to multiple in-out parameters.
在您的示例中,您创建了同一变量的 2 个副本。当函数返回时,它们必须被分配给原始参数。这就是这种情况下的冲突。
关于ios - Inout 参数不允许互相使用别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52362315/