swift - swift inout参数是变量还是指针?

标签 swift inout

我觉得在下面的代码中使用 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.

In-Out Parameters

关于swift - swift inout参数是变量还是指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40567728/

相关文章:

ios - 不能在 inout 函数中使用 SKShapeNode

xcode - 如何添加背景图片

ScrollView 下的 SwiftUI 点击

ios - 显示 ViewControllerB 并关闭 ViewControllerA

json - 解码具有相同信封但不同内容的 JSON 响应

Swift inout 如何在未更改时不复制回属性,以不触发对象 setter

swift - 如何保证 inout 参数不会改变 Type 并且不会在函数中变成 nil

Swift:具有通用函数和约束的 inout

swift - (Swift) 后台计时器使用什么 API 实现?

swift - 替换参数字符串中的字符