加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 04:44:23 所属栏目:百科 来源:网络整理
导读:我觉得在以下代码中使用 swift inout参数有点丢失: var shouldContinue: Bool = truefunc doSomeWork1(shouldContinue: inout Bool){ while shouldContinue { // ERROR: the compiler wants: doSomeWork2(shouldContinue: shouldContinue) doSomeWork2(shou
我觉得在以下代码中使用 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读