Say I have a function with definition
func someInitialiser(paramA : String = "defaultA", paramB : Int = 23, paramC : Double = 99.99) {
//initialisation using parameters
}
I don't want the values within the function to be optional, hence the use of default values for the case that no parameter is given.
However, when I want to call the function, I have a bunch of values to be given as parameters which are indeed optional.
As far as I'm aware you cannot pass a nil value into the function and have it fall back on the default value since the function does not take an optional input.
So it seems to me the only way to do this would be
if paramA == nil && paramB == nil && paramC == nil { someInitialiser() }
if paramA == nil && paramB == nil && paramC != nil { someInitialiser(paramC: paramC) }
if paramA == nil && paramB != nil && paramC == nil { someInitialiser(paramB: paramB) }
if paramA == nil && paramB != nil && paramC != nil { someInitialiser(paramB: paramB, paramC: paramC) }
if paramA != nil && paramB == nil && paramC == nil { someInitialiser(paramA: paramA) }
...
This has up to 2^(number of parameters) possible function calls for those with more parameters, so clearly isn't too nice to write.
It would be much simpler to be able to do something like
someInitialiser(paramA: paramA ?? NULL, paramB: paramB ?? NULL, paramC: paramC ?? NULL)
So that if the values were nil it would pass no parameter at all into the function so that it relies on the default ones in the definition.
I know an alternative is to also provide the default values when the function is called, using coalescence similar to above, though it would be nice to not have to repeat them outside the definition.
Create two functions:
someInitialiser(paramA: String?, paramB: Int?) {
someInitializer(paramA: paramA ?? "defaultA", paramB: paramB ?? 23)
}
someInitialiser(paramA: String, paramB: Int) {
...
}
You are really overthinking the problem. If you want default values for nil
, then ??
is the correct solution. If you don't want to use it outside the function, then you have to let the parameters to be optional and use ??
inside.