arrays - "inout"是否影响数组的写复制行为?

标签 arrays swift

我认为 inout 让你传入一个引用(准确吗?),然后如果引用被多次更改,就像你可能对数组所做的那样,那么数组就不必复制很多次,因为它现在是一个引用类型?

最佳答案

swift 中输入输出参数的语义不同于通过引用传递值。以下是传递输入输出参数时发生的情况:

In-out parameters are passed as follows:

  1. When the function is called, the value of the argument is copied.
  2. In the body of the function, the copy is modified.
  3. 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.

参见 https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Declarations.html#//apple_ref/doc/uid/TP40014097-CH34-ID545

数组在 swift 中是类型,因此在这种情况下它被完全复制。当然,swift 编译器可能会对其进行优化,但无论如何,您可以保证看到与执行完整副本时完全相同的行为。

关于arrays - "inout"是否影响数组的写复制行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46353029/

相关文章:

C# 排除数组对象

python - 将张量分配给多个切片

azure - 如果我使用 MemoryStream,为什么 Azure UploadFromStream 不起作用(可以起作用,但长度等于 0)?

c++ - Qt 中的 2D 游戏 : Initializing monsters and passing dynamically allocated array as a pointer parameter

swift - 如何使用程序集中定义的多个 Storyboard?

swift - 在 Swift 中将数据读入结构

swift - 使用包含链接的默认正文打开 iMessage

javascript - jquery 等于 PHP <?=++$r%2 ?'odd' :'even' ?> 对于 strip 表行?

ios - Swift 将新的堆栈 View 添加到现有堆栈 View

ios - SwiftUI 选择器中选定选项的值不会更新 View