Challenge - 5 Problems
Variadic Parameters Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a variadic sum function
What is the output of this Swift code that uses a variadic parameter to sum numbers?
Swift
func sum(_ numbers: Int...) -> Int { var total = 0 for number in numbers { total += number } return total } print(sum(1, 2, 3, 4))
Attempts:
2 left
💡 Hint
Think about how the function adds all the numbers passed in.
✗ Incorrect
The function sum takes any number of Int values and adds them all together. The call sum(1, 2, 3, 4) returns 10.
❓ Predict Output
intermediate2:00remaining
Variadic parameters with no arguments
What will this Swift code print when calling a variadic function with no arguments?
Swift
func greet(names: String...) { print("Hello, \(names.count) people!") } greet()
Attempts:
2 left
💡 Hint
Variadic parameters can be empty, so count will be zero.
✗ Incorrect
Calling greet() with no arguments means names is an empty array, so names.count is 0.
🧠 Conceptual
advanced2:00remaining
Understanding variadic parameter restrictions
Which statement about variadic parameters in Swift is true?
Attempts:
2 left
💡 Hint
Think about the position of variadic parameters in function definitions.
✗ Incorrect
Swift requires that variadic parameters be the last parameter in the function signature. Only one variadic parameter is allowed.
❓ Predict Output
advanced2:00remaining
Output of variadic function with mixed parameter types
What is the output of this Swift code using a variadic parameter and a normal parameter?
Swift
func describe(age: Int, hobbies: String...) { print("Age: \(age)") print("Hobbies count: \(hobbies.count)") for hobby in hobbies { print(hobby) } } describe(age: 30, hobbies: "Reading", "Swimming")
Attempts:
2 left
💡 Hint
Check how many hobbies are passed and printed.
✗ Incorrect
The function prints the age, then the count of hobbies (2), then each hobby on its own line.
❓ Predict Output
expert2:00remaining
Result of passing an array to a variadic parameter
What will this Swift code print when passing an array to a variadic parameter using the spread operator?
Swift
func multiply(factor: Int, numbers: Int...) -> [Int] { numbers.map { $0 * factor } } let values = [1, 2, 3] let result = multiply(factor: 2, numbers: values...) print(result)
Attempts:
2 left
💡 Hint
The '...' operator expands the array elements as separate arguments.
✗ Incorrect
The array values is expanded into separate arguments 1, 2, 3 for the variadic parameter. Each is multiplied by 2.