0
0
Swiftprogramming~20 mins

In-out parameters for mutation in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift In-Out Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Swift code using in-out parameter?

Consider this Swift function that doubles a number using an in-out parameter. What will be printed?

Swift
func doubleValue(_ number: inout Int) {
    number *= 2
}

var myNumber = 10
doubleValue(&myNumber)
print(myNumber)
A10
BCompilation error
C0
D20
Attempts:
2 left
💡 Hint

Remember that in-out parameters allow the function to modify the original variable.

Predict Output
intermediate
2:00remaining
What error occurs when calling a function with in-out parameter incorrectly?

What error will this Swift code produce?

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

let constantValue = 5
increment(&constantValue)
ACannot pass immutable value as inout argument
BRuntime error: nil value
CNo error, prints 6
DSyntax error: missing &
Attempts:
2 left
💡 Hint

In-out parameters require a variable that can be changed.

🔧 Debug
advanced
2:00remaining
Why does this Swift code cause a compile error with in-out parameters?

Identify the cause of the compile error in this Swift code:

Swift
func swapValues(_ a: inout Int, _ b: inout Int) {
    let temp = a
    a = b
    b = temp
}

var x = 3
swapValues(&x, &x)
ACannot pass the same variable twice as inout parameters
BMissing & before second argument
CFunction swapValues requires return type
DNo error, swaps values correctly
Attempts:
2 left
💡 Hint

Think about what happens if you try to modify the same variable twice at once.

Predict Output
advanced
2:00remaining
What is the output of this nested in-out parameter mutation?

What will be printed by this Swift code?

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

func doubleAndAddOne(_ number: inout Int) {
    number *= 2
    addOne(&number)
}

var value = 4
doubleAndAddOne(&value)
print(value)
A10
B8
C9
DCompilation error
Attempts:
2 left
💡 Hint

Follow the changes step by step: first double, then add one.

🧠 Conceptual
expert
2:00remaining
What is the main reason Swift uses in-out parameters instead of returning mutated values?

Why does Swift use in-out parameters for mutation instead of just returning a new value?

ABecause Swift does not support returning values from functions
BTo allow functions to modify variables directly without copying large data structures
CTo prevent any changes to variables outside the function
DBecause in-out parameters are required for all functions in Swift
Attempts:
2 left
💡 Hint

Think about performance and memory when working with big data.