Question re inout in Swift

I just read the following text in my Swift instruction book:

inout before the parameter type indicates that this parameter should be copied in, that local copy used within the function, and copied back out when the function returns.

Can someone please explain what this means? I understand pass-by-value (to copy a value to another location in memory). But I don't understand the above quote from my Swift book.

...this parameter should be copied in...

Copied in or into where?

...and copied back out...

What do they mean by "copied back out"? (I don't understand how something is "copied out".)

Could someone please fill me in on what this text means? I'm a beginner, so please keep that in mind when explaining. Thank you so much.

Example:

var x = 0

func increment(_ number: inout Int) {
  number += 1
}

increment(&x)
// x is now 1
  1. The value of the argument (x) is copied into the parameter (number).
  2. When the function ends, the value of the parameter (number) is copied back out to the variable you passed in-out as an argument (x).

You can view this as pass-by-reference, but I believe the author deliberately avoided this term. inout may be implemented differently, so we should assume it's implemented as two copy operations (that may or may not be optimized to pass-by-reference).

4 Likes

The distinction becomes more pronounced if you use a computed property:

var x: Int {
  get {
    print("getter")
    return 0
  }

  set {
    print("setter \(newValue)")
  }
}

increment(&x)

This will "copy in" the value of calling the getter for x, invoke increment, then "copy out" the final value of increment's argument by passing it to the setter for x, causing this to get printed:

getter
setter 1
7 Likes

Thank you, I appreciate it!

Terms of Service

Privacy Policy

Cookie Policy