user8388622
user8388622

Reputation:

Does "inout" affect array's copy on write behaviour?

I think inout makes you passes in a reference (is that accurate?), then if the reference gets changed many times, as you might do with an array, the array then does not have to copied many times because its now a reference type?

Upvotes: 0

Views: 398

Answers (2)

gnasher729
gnasher729

Reputation: 52530

If you want to pass an array by reference and allow the called function to modify elements quickly, you have the choice of either explictly creating an NSMutableArray, or creating a class where instances have an array as their single member.

Upvotes: 0

algrid
algrid

Reputation: 5954

The semantics for in-out parameters in swift is different from passing value by reference. Here's exactly what happens when you're passing an in-out parameter:

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.

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

Array is value type in swift so it's fully copied in this scenario. Of course the swift compiler may optimize that but anyway you're guaranteed to see exact same behavior as it'd be with full copies performed.

Upvotes: 2

Related Questions