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中更详细地讨论了这种行为.