Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default optional parameter in Swift function

When I set firstThing to default nil this will work, without the default value of nil I get a error that there is a missing parameter when calling the function.

By typing Int? I thought it made it optional with a default value of nil, am I right? And if so, why doesn't it work without the = nil?

func test(firstThing: Int? = nil) {     if firstThing != nil {         print(firstThing!)     }     print("done") } test() 
like image 567
RickBrunstedt Avatar asked May 18 '16 17:05

RickBrunstedt


People also ask

What are default and optional parameters?

The default value of an optional parameter is a constant expression. The optional parameters are always defined at the end of the parameter list. Or in other words, the last parameter of the method, constructor, etc. is the optional parameter.

Is it possible to give a default value to a function parameter Swift?

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. // the value of parameterWithDefault is 12 inside the function body.

What is an Optional parameter in a function?

What are Optional Parameters? By definition, an Optional Parameter is a handy feature that enables programmers to pass less number of parameters to a function and assign a default value.

How do I set optional parameters?

Using Optional Attribute Here for the [Optional] attribute is used to specify the optional parameter. Also, it should be noted that optional parameters should always be specified at the end of the parameters. For ex − OptionalMethodWithDefaultValue(int value1 = 5, int value2) will throw exception.


1 Answers

Optionals and default parameters are two different things.

An Optional is a variable that can be nil, that's it.

Default parameters use a default value when you omit that parameter, this default value is specified like this: func test(param: Int = 0)

If you specify a parameter that is an optional, you have to provide it, even if the value you want to pass is nil. If your function looks like this func test(param: Int?), you can't call it like this test(). Even though the parameter is optional, it doesn't have a default value.

You can also combine the two and have a parameter that takes an optional where nil is the default value, like this: func test(param: Int? = nil).

like image 132
EmilioPelaez Avatar answered Oct 23 '22 14:10

EmilioPelaez