我觉得在下面的代码中使用 swift inout 参数有点迷茫:
var shouldContinue: Bool = true
func doSomeWork1(shouldContinue: inout Bool)
{
while shouldContinue
{
// ERROR: the compiler wants: doSomeWork2(shouldContinue: &shouldContinue)
doSomeWork2(shouldContinue: shouldContinue)
}
}
func doSomeWork2(shouldContinue: inout Bool)
{
while shouldContinue
{
}
}
为什么编译器需要 doSomeWork2(shouldContinue: &shouldContinue)
而不是 the compiler wants: doSomeWork2(shouldContinue: shouldContinue)
? shouldContinue
不是已经是 doSomeWork1() 范围内的指针了吗???
最佳答案
成为指针只是输入输出参数优化过程的副作用。它们实际上以不同的方式工作,使用copy-in copy-out 行为。所以在函数内部,参数就像常规变量一样对待,而不是指针。如果将它传递给另一个采用 inout 参数的函数,则必须将其标记为这样。
In-out parameters are passed as follows:
When the function is called, the value of the argument is copied.
In the body of the function, the copy is modified.
When the function returns, the copy’s value is assigned to the original argument.
This behavior is known as copy-in copy-out or call by value result. For example, when a computed property or a property with observers is passed as an in-out parameter, its getter is called as part of the function call and its setter is called as part of the function return.
As an optimization, when the argument is a value stored at a physical address in memory, the same memory location is used both inside and outside the function body. The optimized behavior is known as call by reference; it satisfies all of the requirements of the copy-in copy-out model while removing the overhead of copying. Write your code using the model given by copy-in copy-out, without depending on the call-by-reference optimization, so that it behaves correctly with or without the optimization.
关于swift - swift inout参数是变量还是指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40567728/