我认为 inout 让你传入一个引用(准确吗?),然后如果引用被多次更改,就像你可能对数组所做的那样,那么数组就不必复制很多次,因为它现在是一个引用类型?
最佳答案
swift 中输入输出参数的语义不同于通过引用传递值。以下是传递输入输出参数时发生的情况:
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.
数组在 swift 中是值类型,因此在这种情况下它被完全复制。当然,swift 编译器可能会对其进行优化,但无论如何,您可以保证看到与执行完整副本时完全相同的行为。
关于arrays - "inout"是否影响数组的写复制行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46353029/