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

swift inout参数是变量还是指针?,第1张

概述我觉得在以下代码中使用 swift inout参数有点丢失: var shouldContinue: Bool = truefunc doSomeWork1(shouldContinue: inout Bool){ while shouldContinue { // ERROR: the compiler wants: doSomeWork2(shouldCo 我觉得在以下代码中使用 swift inout参数有点丢失:

var shouldContinue: Bool = truefunc 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

总结

以上是内存溢出为你收集整理的swift inout参数是变量还是指针?全部内容,希望文章能够帮你解决swift inout参数是变量还是指针?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/web/1008070.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-22
下一篇 2022-05-22

发表评论

登录后才能评论

评论列表(0条)

保存