I have a function with default parameters in swift.
func test(string: String = "", middleString: String = "", endString: String = "") -> Void { // do stuff }
I want to pass in variables that will be optional strings.
let string: String? let middleString: String? let endString: String?
How do I make it so that if the parameters are nil, use the default parameters. If not, then use the values within the optionals.
test(string, middleString: middleString, endString: endString)
By default, all parameters of a method are required. A method that contains optional parameters does not force to pass arguments at calling time. It means we call method without passing the arguments. The optional parameter contains a default value in function definition.
In Swift, we can provide default values to function parameters.
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.
You'll have to use Optional strings String?
as your argument type, with default values of nil
. Then, when you call your function, you can supply a string or leave that argument out.
func test(string: String? = nil, middleString: String? = nil, endString: String? = nil) -> Void { let s = string ?? "" let mS = middleString ?? "" let eS = endString ?? "" // do stuff with s, mS, and eS, which are all guaranteed to be Strings }
Inside your function, you'll have to check each argument for nil
and replace with a default value there. Using the ??
operator makes this easy.
You can then call your function by supplying all arguments, no arguments, or only the ones you want to include:
test(string: "foo", middleString: "bar", endString: "baz") test() test(string: "hello", endString: "world")
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