0
0
Swiftprogramming~5 mins

Variadic parameters in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a variadic parameter in Swift?
A variadic parameter allows a function to accept zero or more values of a specified type as input. It is written with three dots (...) after the parameter's type.
Click to reveal answer
beginner
How do you declare a variadic parameter in a Swift function?
You add three dots (...) after the parameter type. For example: <br>func sum(numbers: Int...) means the function can take many Int values.
Click to reveal answer
intermediate
Can a Swift function have more than one variadic parameter?
No, a function can have only one variadic parameter, and it must be the last parameter in the function's parameter list.
Click to reveal answer
beginner
How do you access the values passed to a variadic parameter inside the function?
Inside the function, the variadic parameter is treated as an array of the specified type. You can loop over it or access elements by index.
Click to reveal answer
beginner
Example: What does this Swift function do?<br>
func greet(names: String...) {<br>  for name in names {<br>    print("Hello, \(name)!")<br>  }<br>}
This function takes any number of names as input and prints a greeting for each one. For example, calling greet(names: "Anna", "Bob") prints:<br>Hello, Anna!<br>Hello, Bob!
Click to reveal answer
How do you declare a variadic parameter in Swift?
AAdd three dots (...) after the parameter type
BUse square brackets [] around the parameter
CUse an asterisk * before the parameter name
DDeclare the parameter as optional with ?
How many variadic parameters can a Swift function have?
ATwo, but only if they are of the same type
BAny number, anywhere in the parameter list
COnly one, and it must be last
DNone, Swift does not support variadic parameters
Inside a function, a variadic parameter is treated as:
AAn array of the parameter's type
BA single value of the parameter's type
CA dictionary with keys as indexes
DA tuple of fixed size
What happens if you call a function with a variadic parameter but pass no arguments for it?
AThe function throws an error
BThe variadic parameter is an empty array
CThe function ignores the parameter
DThe function uses a default value
Which of these is a valid function declaration with a variadic parameter?
Afunc add(numbers: [Int]...)
Bfunc add(...numbers: Int)
Cfunc add(numbers: Int, others: Int...)
Dfunc add(numbers: Int...)
Explain what a variadic parameter is and how you use it in a Swift function.
Think about how you can pass many values to one parameter.
You got /3 concepts.
    Describe the rules and limitations of using variadic parameters in Swift functions.
    Consider function parameter order and count.
    You got /3 concepts.