Optional Parameters With Default Values In Swift Explained

By Eddy Chung

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.

How To Use Optional Parameters With Default Values

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 Use Optional Parameters With Default Values

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!

Alternatives to Optional Parameters With Default Values

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
If you liked this post, you'll love my free guide: Secrets To iOS Development. Speed up your learning curve - hundreds of students have already downloaded. Thanks for reading!
Profile Picture of Eddy Chung

Eddy Chung

I am a professional iOS developer in Silicon Valley. I teach iOS development on ZeroToAppStore.com. If you'd like to learn more about me click here or you can contact me at: eddy@zerotoappstore.com

Similar Posts