0
0
Swiftprogramming~10 mins

Variadic parameters in Swift - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a function that accepts a variable number of integers.

Swift
func sum(numbers: [1]) -> Int {
    return numbers.reduce(0, +)
}
Drag options to blanks, or click blank then click option'
A...
B...Int
C...Ints
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting the three dots (...) before the type.
Using plural forms like Ints which is invalid syntax.
2fill in blank
medium

Complete the code to call the variadic function with three integer arguments.

Swift
let result = sum(numbers: [1])
Drag options to blanks, or click blank then click option'
A1, 2, 3
B[1, 2, 3]
C(1, 2, 3)
D"1, 2, 3"
Attempts:
3 left
💡 Hint
Common Mistakes
Passing an array instead of comma-separated values.
Passing a tuple or string instead of separate values.
3fill in blank
hard

Fix the error in the function definition to correctly accept a variable number of strings.

Swift
func greet(names: [1]) {
    for name in names {
        print("Hello, \(name)!")
    }
}
Drag options to blanks, or click blank then click option'
A...Strings
B...
C...String
Attempts:
3 left
💡 Hint
Common Mistakes
Using plural type names like Strings.
Omitting the three dots.
4fill in blank
hard

Fill both blanks to create a function that returns the average of a variable number of Double values.

Swift
func average(values: [1]) -> Double {
    let total = values[2]reduce(0.0, +)
    return total / Double(values.count)
}
Drag options to blanks, or click blank then click option'
A...
B...Double
C.
D?
Attempts:
3 left
💡 Hint
Common Mistakes
Using a question mark instead of a dot before reduce.
Omitting the three dots in the parameter.
5fill in blank
hard

Fill all three blanks to define and call a function that prints all provided strings separated by commas.

Swift
func printAll(items: [1]) {
    let combined = items[2]joined(separator: [3])
    print(combined)
}

printAll(items: "apple", "banana", "cherry")
Drag options to blanks, or click blank then click option'
A...String
B.
C", "
D...
Attempts:
3 left
💡 Hint
Common Mistakes
Using '...' instead of '...String' in the parameter.
Forgetting the dot before joined.
Using wrong separator string.