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()
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.
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 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.
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.
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)
.
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