Default Parameter Values in Swift 🎯

beginner
14 min

Default Parameter Values in Swift 🎯

Welcome to your Swift journey! Today, we'll dive into understanding Default Parameter Values, a powerful feature in Swift that makes function calls more flexible.

What are Default Parameter Values? 📝

Default Parameter Values allow you to assign a predefined value to a function parameter. If no value is provided when calling the function, Swift uses the default value you've set. This feature makes functions more adaptable and easier to use.

Why Default Parameter Values? 💡

Default Parameter Values make functions more versatile and user-friendly. They allow callers to use functions with or without specifying certain parameters, reducing the number of required arguments and making the function more adaptable.

Syntax for Default Parameter Values 📝

To define a function with default parameter values, simply assign a value to the parameter within the function definition. Here's an example:

swift
func greet(person: String, greeting: String = "Hello") { print("\(greeting), \(person)!") }

In the above example, the function greet has two parameters: person and greeting. The greeting parameter has a default value of "Hello".

Using Default Parameter Values 📝

Now let's see how to use the function with and without specifying the greeting parameter:

swift
greet(person: "John") // Output: Hello, John! greet(person: "John", greeting: "Hi") // Output: Hi, John!

In the first call, we only provided a value for the person parameter, so Swift used the default value "Hello" for greeting. In the second call, we provided a custom greeting, so Swift used that instead.

Pro Tip 💡

You can have multiple parameters with default values. Just remember to list them from left to right, with the parameters that have default values coming later.

Quiz 🎯

Quick Quiz
Question 1 of 1

Which of the following function calls will output "Bye, John"?


By understanding Default Parameter Values, you'll be able to create more adaptable functions that can be used in various scenarios. Stay tuned for more Swift tutorials! 🚀

Happy coding! 💻