0
0
Swiftprogramming~20 mins

Variadic parameters in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Variadic Parameters Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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))
A0
B1234
C10
DError: variadic parameters cannot be used this way
Attempts:
2 left
💡 Hint
Think about how the function adds all the numbers passed in.
Predict Output
intermediate
2: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()
ACompile error: missing arguments
BHello, 1 people!
CHello, nil people!
DHello, 0 people!
Attempts:
2 left
💡 Hint
Variadic parameters can be empty, so count will be zero.
🧠 Conceptual
advanced
2:00remaining
Understanding variadic parameter restrictions
Which statement about variadic parameters in Swift is true?
AVariadic parameters must be the last parameter in the function signature.
BA function can have multiple variadic parameters.
CVariadic parameters can only accept Int values.
DVariadic parameters automatically unwrap optional values.
Attempts:
2 left
💡 Hint
Think about the position of variadic parameters in function definitions.
Predict Output
advanced
2: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")
A
Age: 30
Hobbies count: 0
B
Age: 30
Hobbies count: 2
Reading
Swimming
C
Age: 30
Hobbies count: 1
Reading, Swimming
DCompile error: variadic parameter must be last
Attempts:
2 left
💡 Hint
Check how many hobbies are passed and printed.
Predict Output
expert
2: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)
A[2, 4, 6]
B[1, 2, 3, 2]
C[4, 6, 8]
DError: cannot use '...' to expand array here
Attempts:
2 left
💡 Hint
The '...' operator expands the array elements as separate arguments.