0
0
Swiftprogramming~20 mins

Default parameter values in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Default Parameter Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of function with default parameters
What is the output of this Swift code when calling greet() without any arguments?
Swift
func greet(name: String = "Friend", greeting: String = "Hello") {
    print("\(greeting), \(name)!")
}
greet()
AError: Missing arguments
BHello, !
CFriend, Hello!
DHello, Friend!
Attempts:
2 left
💡 Hint
Check the default values assigned to the parameters in the function definition.
Predict Output
intermediate
2:00remaining
Function call with one default parameter overridden
What will be printed when calling greet(name: "Alice") with the function below?
Swift
func greet(name: String = "Friend", greeting: String = "Hello") {
    print("\(greeting), \(name)!")
}
greet(name: "Alice")
AHello, Alice!
BAlice, Hello!
CError: Missing argument for greeting
DHello, Friend!
Attempts:
2 left
💡 Hint
Only the name parameter is provided; the other uses its default.
Predict Output
advanced
2:00remaining
Output with default parameters and argument labels
What is the output of this Swift code?
Swift
func calculateArea(width: Int = 10, height: Int = 5) -> Int {
    return width * height
}
print(calculateArea(height: 3))
A50
BError: Missing argument for width
C30
D15
Attempts:
2 left
💡 Hint
The width parameter uses its default value.
Predict Output
advanced
2:00remaining
Default parameter with mutable variable
What will be printed after this code runs?
Swift
var count = 5
func increment(by amount: Int = count) -> Int {
    return amount + 1
}
count = 10
print(increment())
AError: Cannot use variable 'count' as default parameter
B11
C5
D6
Attempts:
2 left
💡 Hint
Swift requires default parameter values to be compile-time constants; variables are not allowed.
🧠 Conceptual
expert
2:00remaining
Why default parameter values must be compile-time constants
Why does Swift require default parameter values to be compile-time constants or literals?
ABecause Swift does not support functions with optional parameters
BBecause default values are evaluated once at compile time and cannot depend on runtime variables
CBecause default values are ignored during function calls
DBecause default values must be mutable to change during execution
Attempts:
2 left
💡 Hint
Think about when the default value is set and how it relates to program execution.