Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple unnamed parameters in Swift methods

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?

like image 594
exists-forall Avatar asked Dec 07 '14 00:12

exists-forall


People also ask

What is Variadic parameters in Swift?

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.

How is an external parameter used with a function in Swift?

“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.”

What is #function Swift?

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.

What is argument label in Swift?

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.


1 Answers

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
    }
}
like image 134
Nate Cook Avatar answered Sep 19 '22 18:09

Nate Cook