Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional Default Parameter in Swift

Tags:

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)

like image 978
William Bing Hua Avatar asked Jul 08 '15 19:07

William Bing Hua


People also ask

What are default and optional parameters?

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.

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

In Swift, we can provide default values to function parameters.

What is Variadic parameters in Swift?

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.


1 Answers

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") 
like image 182
justinpawela Avatar answered Oct 18 '22 12:10

justinpawela