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()范围内的指针?
解决方法
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.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。