Swift's string type is a value type. If you create a new String value, that String value is copied when it is passed to a function or method, or when it is assigned to a constant or variable.
它在分配给常量或变量时被复制,这对我来说很有意义。但是当一个值类型的变量传递给一个函数时,它也会被复制,这让我很困惑。
问题
将值类型变量传递给函数时如何复制它?什么样的“空间”持有这个副本?它是在幕后无形地创建的某种临时变量,并在函数处理后被销毁吗?
谢谢
最佳答案
将值类型传递给函数时,可以将其视为将其分配给作用域为该函数的局部变量,因此复制行为类似于仅分配一个新的局部变量。
关于复制到哪里,我们应该认识到,复制行为其实比听起来要复杂。正如他们在 Building Better Apps with Value Types in Swift (WWDC 2015, Session 414) 中指出的那样, “副本很便宜”:
Copying a low-level, fundamental type is constant time
Int
,Double
, etc.Copying a struct, enum, or tuple of value types is constant time
CGPoint
, etc.Extensible data structures use copy-on-write
Copying involves a fixed number of reference-counting operations
String
,Array
,Set
,Dictionary
, etc.
关于最后一点,Swift 在幕后做了一些巧妙的处理,避免每次引用它们时都复制可扩展值类型,而只是指向原始引用,但跟踪有多少引用,实际上只有制作副本 (a) 以书面形式;其中 (b) 有不止一个引用。此行为在 that video 中有更详细的讨论。 .
关于swift - 值类型变量在传递给函数时如何被复制,这个副本是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39000140/