user5669940
user5669940

Reputation:

How to make a function parameter optional (to avoid calling all parameters each time)

I want to make a function parameter optional, so when I call the function I don't always have to have all three parameters, eg:

func doSomething(name: String, age: String, gender: String?)

In that case, I'd want to not always have to specify a gender, so I could call:

doSomething(name: "Dave", age: 25, gender: "Male")

or leave out the gender and just call:

doSomething(name: "Dave", age: 25)

But when I do, it tells me it unexpectedly found nil, or that there's a missing parameter, how can I make the 'gender' input optional?

Upvotes: 2

Views: 542

Answers (2)

hannad
hannad

Reputation: 822

Just give it a default value.

func doSomething(name: String, age: String, gender: String? = "Male")

or

func doSomething(name: String, age: String, gender: String? = nil)

Quoted from the Docs

You can define a default value for any parameter in a function by assigning a value to the parameter after that parameter’s type. If a default value is defined, you can omit that parameter when calling the function.

UPDATE: Please note that declaring a variable that is of an optional type does not mean that you can omit this parameter when calling the function. It just means that this parameter can hold either a value depending on its type, or a nil.

Upvotes: 6

Andreas Utzinger
Andreas Utzinger

Reputation: 402

Another option is to do something like the designated initializers pattern, like so:

class Person {

    func doSomething(name: String, age: String, gender: String?) {
        // do something with these informations
    }

    func doSomething(name: String, age: String) {
        self.doSomething(name, age: age, gender: nil)
    }

}

Then you can ommit the last parameter, as your method calls the designated method in return

Upvotes: 1

Related Questions