`diff Swift C++`: passing arguments

In C++ you can pass arguments in 4 different ways:

  1. By value
  2. By pointer
  3. By reference
  4. By rvalue reference

On top of that you often want to use const (or other modifiers) to signal that passed values or objects shouldn't (not cannot) be changed. On top of that you can modify member functions (or methods as they are often called in other languages) to be const or not which again signals that those shouldn't (again not cannot) change the state of the object they are bound to.

I love C++ but writing correct code for it is very hard and requires constant vigilance.

In Swift you can pass arguments in only two ways:

  1. By value
  2. By reference

And the rules when is passed what are very easy: instances of struct and enum are always passed by value whereas instances of class are always passed by reference. Values for built-in types like Int are also always passed by value.

If you want to pass in a value that you want modified and updated by the function, then Swift has inout keyword. However, The Swift Programming Language book states that:

“An in-out parameter has a value that is passed in to the function, is modified by the function, and is passed back out of the function to replace the original value.”

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/cl/jEUH0.l

To me that sounds that there are two copy operations involved here (one when the value is passed, another when it is passed back out to replace the original value). In C++ this inefficiency doesn't exist so I wanted to confirm that it really works like that. I'm happy to report that it doesn't - my experiments have consistently shown that the inout values are passed by reference (and the ampersand is probably there to visually indicate the same)


Ivan Erceg

Software shipper, successful technical co-founder, $1M Salesforce Hackathon 2014 winner