Consider this Swift function that doubles a number using an in-out parameter. What will be printed?
func doubleValue(_ number: inout Int) { number *= 2 } var myNumber = 10 doubleValue(&myNumber) print(myNumber)
Remember that in-out parameters allow the function to modify the original variable.
The function doubles the value of myNumber by modifying it directly through the in-out parameter. So the printed value is 20.
What error will this Swift code produce?
func increment(_ value: inout Int) { value += 1 } let constantValue = 5 increment(&constantValue)
In-out parameters require a variable that can be changed.
You cannot pass a constant (let) as an in-out parameter because it cannot be mutated.
Identify the cause of the compile error in this Swift code:
func swapValues(_ a: inout Int, _ b: inout Int) { let temp = a a = b b = temp } var x = 3 swapValues(&x, &x)
Think about what happens if you try to modify the same variable twice at once.
Swift forbids passing the same variable as multiple in-out arguments simultaneously because it causes conflicting access to the variable.
What will be printed by this Swift code?
func addOne(_ number: inout Int) { number += 1 } func doubleAndAddOne(_ number: inout Int) { number *= 2 addOne(&number) } var value = 4 doubleAndAddOne(&value) print(value)
Follow the changes step by step: first double, then add one.
The value starts at 4, doubles to 8, then addOne adds 1, resulting in 9.
Why does Swift use in-out parameters for mutation instead of just returning a new value?
Think about performance and memory when working with big data.
In-out parameters allow functions to modify variables directly, which can be more efficient than returning new copies, especially for large data.