inout parameters

Swift language Mid-level Swift 5.0+ iOS 17+ Reviewed By Alok Singh

Predict the output

What does this print?

struct Temperature {
    var celsius = 10.0
    var fahrenheit: Double {
        get { celsius * 9 / 5 + 32 }
        set { celsius = (newValue - 32) * 5 / 9 }
    }
}
func warm(_ x: inout Double) { x += 18 }
var t = Temperature()
warm(&t.fahrenheit)
print(t.celsius)
Options
Hint 1 of 1

What happens when the function returns?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: B 20.0

Correct. 50°F is read, becomes 68°F, and the setter writes back 20°C.

Why not the others?
  • A It doesn't compile: computed properties can't be inout. Read-write computed properties can be passed as inout; only get-only ones can't.
  • C 10.0. The setter runs on write-back and updates celsius.
  • D 28.0. 18 is added to the Fahrenheit value, not to Celsius.

30-second answer

An inout parameter lets a function change a caller's variable. The value is copied in, modified, and written back when the function returns (copy-in copy-out). You pass a mutable variable or a read-write property with &, including computed properties with a setter. Constants, literals and get-only properties can't be passed.

Practise saying it · 30 s. No recording, just a timer

Explain inout.

Say your answer out loud, then check which of these points you covered:

  • Copy-in copy-out
  • Pass with &
  • Read-write computed properties are allowed

Deep dive

Property observers fire on write-back.

Exclusivity rules forbid overlapping access, such as passing the same variable twice.

Don't capture an inout parameter in an escaping closure.

Prefer returning a new value unless mutation in place is clearer or faster.

Common mistakes

  • Thinking computed properties can't be inout.
  • Passing the same variable as two inout arguments.

Senior take & follow-ups

Seniors explain copy-in copy-out and exclusivity.

Follow-up questions

Think of your answer first, then open the hint.

  1. What is the law of exclusivity?

    Show hint

    No overlapping writes to the same variable.

  2. Is inout pass-by-reference?

    Show hint

    Semantically copy-in copy-out, often optimized to a reference.

Suggest a fix if something here is wrong or out of date.