Optional Default Parameter in Swift
Try this:
test(string: string ?? "", middleString: middleString ?? "", endString: endString ?? "")
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")