SLN SLN - 1 year ago 68
Swift Question

How a value typed variable is copied when it is passed to a function, what hold this copy?

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.

It is copied when assigned to a constant or variable, this makes sense for me. But when a value typed variable passed to a function it also get copied, this confuses me.


How it gets copied when passing a value typed variable to a function? what kind of "space" holds this copy? Is it some sort of temporary variables invisibly created behind the scene and after the process of the function it gets destroyed?


Rob Rob
Answer Source

When passing value type to a function, think of it like assigning it to a local variable whose scope is that function, so the copy behavior is analogous to just assigning a new local variable.

Regarding where it is copied, we should recognize that the copy behavior is actually more complicated than it sounds. As they point out in Building Better Apps with Value Types in Swift (WWDC 2015, Session 414), "Copies are Cheap":

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.

Regarding that last point, behind the scenes Swift does some sleight of hand that avoids copying extensible value types every time they're referenced, but rather just points to the original reference but keeps track of how many references there are and actually only makes copies (a) upon write; where (b) there's more than one reference. This behavior is discussed in more detail in that video.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download