Hint: Remember: inout goes after parameter name, before type [OK]
Common Mistakes:
Placing inout before parameter name
Swapping parameter name and type order
Using invalid syntax like 'inout value in Int'
3.
What will be the output of this Swift code?
func doubleValue(_ number: inout Int) {
number *= 2
}
var myNum = 5
doubleValue(&myNum)
print(myNum)
medium
A. 5
B. Error: missing & in function call
C. 10
D. Error: cannot modify constant
Solution
Step 1: Understand the function behavior
The function doubles the value of the passed variable by multiplying it by 2.
Step 2: Trace the code execution
Variable myNum starts at 5, is passed with & to allow mutation, so after the function call it becomes 10.
Final Answer:
10 -> Option C
Quick Check:
In-out parameter doubles 5 to 10 [OK]
Hint: Use & when calling to let function change variable [OK]
Common Mistakes:
Forgetting & when calling function
Expecting original value unchanged
Confusing parameter passing with copy
4.
Identify the error in this Swift code snippet:
func increment(_ value: inout Int) {
value += 1
}
let number = 10
increment(&number)
medium
A. Cannot pass a constant as an inout parameter.
B. Missing & when calling the function.
C. Function parameter should not be inout.
D. Function must return the new value.
Solution
Step 1: Check variable mutability
The variable number is declared with let, making it a constant.
Step 2: Understand inout parameter requirements
Inout parameters require a variable that can be modified, so constants cannot be passed.
Final Answer:
Cannot pass a constant as an inout parameter. -> Option A
Quick Check:
Inout needs variable, not constant [OK]
Hint: Only variables (var), not constants (let), can be inout [OK]
Common Mistakes:
Trying to pass constants as inout parameters
Forgetting & when calling function
Thinking function must return value when using inout
5.
You want to write a function swapValues that swaps two integers using inout parameters. Which of the following implementations correctly swaps the values?
To swap two values, you need a temporary variable to hold one value while assigning the other.
Step 2: Check each option
var temp = a
a = b
b = temp correctly declares a temporary variable with var and swaps values safely. let temp = a
temp = b
b = temp uses let which is immutable and causes error. a = b
b = a overwrites a before assigning b. a = b
b = a - b
a = a - b uses arithmetic swap but is more complex and not recommended here.
Final Answer:
var temp = a
a = b
b = temp -> Option D
Quick Check:
Use temp variable with var to swap values [OK]
Hint: Use a temporary variable declared with var to swap values [OK]
Common Mistakes:
Using let for temporary variable causing immutability error
Overwriting one variable before saving its value
Trying to swap without a temporary variable incorrectly
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.