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)而不是编译器想要:doSomeWork2(shouldContinue:shouldContinue)?是不是应该继续在doSomeWork1()范围内的指针?

解决方法

作为指针只是inout参数的优化过程的副作用.它们实际上使用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

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...