I want to make a method that can take variable number of parameters. Kind of like in javascript where I can get all the parameters using arguments
keyword inside the function. How can I do this in Swift?
My main purpose is to allow all overloaded constructors to go to one method even if it has no parameters passed in it at all.
class Counter {
var count: Int = 0
func incrementBy(amount: Int, numberOfTimes: Int) {
count += amount * numberOfTimes
}
}
Information can be passed to methods as parameter. Parameters act as variables inside the method. Parameters are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma.
Syntax of VarargsA variable-length argument is specified by three periods or dots(…). This syntax tells the compiler that fun( ) can be called with zero or more arguments. As a result, here, a is implicitly declared as an array of type int[].
In Swift, variadic parameters are the special type of parameters available in the function. It is used to accept zero or more values of the same type in the function. It is also used when the input value of the parameter is varied at the time when the function is called.
Swift's functions have a single return type, such as Int or String , but that doesn't mean we can only return a single value. In fact, there are two ways we can send back multiple pieces of data: Using a tuple, such as (name: String, age: Int) Using some sort of collection, such as an array or a dictionary.
There is an example of that in the Swift iBook, page 17:
func sumOf(numbers: Int...) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
sumOf() // returns 0
sumOf(1,2) // returns 3
sumOf(42, 597, 12) // returns 651
Varargs are great, but they aren't really for optional parameters that mean different things, as seen in the Counter
example in the question. Function overloading can be kind of excessive, though: it breaks the coupling between a function definition and its true implementation.
What you might want here is default values for parameters:
func incrementBy(amount: Int, numberOfTimes num: Int = 1) {
count += amount * num
}
Now you'll get the same behavior calling either incrementBy(2, numberOfTimes:1)
or incrementBy(2)
(incrementing by two, once).
Parameters with default values must come last in in the func/method signature, and must be labeled. This is discussed a few subsections down under Function Parameter Names in the book.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With