Optional parameters with default values is a powerful feature of Swift functions.
This allows you to add additional parameters without needing to modify all existing functions calls.
To create a function with optional parameters that have default values, simply define them after your non-optional parameters.
func sendGreeting(name: String, greeting: String = "Hello, ") {
print("\(greeting)\(name)")
}
sendGreeting(name: "Eddy")
Since we didn’t specify the greeting
parameter, this will output:
Hello, Eddy
However, if we call the function like so:
sendGreeting(name: "Eddy", greeting: "Heya, ")
We’ll get the following output:
Heya, Eddie
Simple enough right? The only thing to remember is to always put your optional parameters with default values at the end, after your required parameters. This is a best practice, however Swift doesn’t enforce this rule.
This code will still work:
func sendGreeting(greeting: String = "Hello, ", name: String) {
print("\(greeting)\(name)")
}
sendGreeting(name: "Eddy")
Why would we use optional parameters with default? The best case to use an optional parameter with a default value is when you want to modify a function but it is being called in many different places.
Instead of having to modify all these function calls, you can simply add an optional parameter with a default value. That way all the previous function calls will work fine and your new function call will work as well!
Another option instead of using optional parameters with default values is to create two functions, one that calls the other:
func sendGreeting(name: String) {
sendGreeting(name: name, greeting: "Hello, ")
}
func sendGreeting(name: String, greeting: String) {
print("\(greeting)\(name)")
}
sendGreeting(name: "Eddy")
Hello, Eddy
This will achieve an identical result. You can of course call the second function:
sendGreeting(name: "Eddy", greeting: "Heya, ")
Resulting in:
Heya, Eddy
The Complete iOS App Development Bootcamp
Disclosure: This website may contain affiliate links, meaning when you click the links and make a purchase, we receive a commission.