As far as I can tell, Swift functions have unnamed parameters by default, but Swift methods do not (excluding the first parameter). For example, given the following definitions:
func foo(a: Int, b: Int) -> Int {
return a + b
}
class MyClass {
func bar(a: Int, b: Int) -> Int {
return a + b
}
}
I have to call foo
with unnamed parameters:
foo(10, 20) // fine
foo(a: 10, 20) // error
foo(10, b: 20) // error
foo(a: 10, b: 20) // error
and I have to call bar
with the first argument unnamed, and the second argument named:
MyClass().bar(10, b: 20) // fine
MyClass().bar(10, 20) // error
MyClass().bar(a: 10, b: 20) // error
MyClass().bar(a: 10, 20) // error
I understand that I can make any unnamed parameter named by using the #
symbol, but my question is: is there any way I can make both arguments to bar
unnamed?
In other words, I would like to declare bar
in such a way that I can call it like an ordinary function:
MyClass().bar(10, 20)
Is this possible in Swift? If so, how?
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.
“The use of external parameter names can allow a function to be called in an expressive, sentence-like manner, while still providing a function body that is readable and clear in intent.”
A function is a set of statements organized together to perform a specific task. A Swift 4 function can be as simple as a simple C function to as complex as an Objective C language function. It allows us to pass local and global parameter values inside the function calls.
The argument label is used when calling the function; each argument is written in the function call with its argument label before it. The parameter name is used in the implementation of the function. By default, parameters use their parameter name as their argument label.
Yes, you prefix the second parameter name with _
to have it be anonymous:
class MyClass {
func bar(a: Int, _ b: Int) -> Int {
return a + b
}
}
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