Defining default parameters in Swift functions
In Swift, you can define default parameters by assigning a default value to one or more parameters in a function declaration. This allows you to call the function without explicitly passing values for those parameters, and the default values will be used instead.
Syntax for Default Parameters
To define default parameters, simply assign a value to the parameter in the function declaration using the = operator:
func functionName(parameterName: ParameterType = DefaultValue)
// Function body
}Example of Default Parameters
Here’s an example of a function that uses default parameters:
func greet(name: String = "Guest", greeting: String = "Hello")
print("\(greeting), \(name)!")
}
// Calling the function with no arguments
greet()
// Output: Hello, Guest!
// Calling the function with one argument
greet(name: "Alice")
// Output: Hello, Alice!
// Calling the function with both arguments
greet(name: "Bob", greeting: "Hi")
// Output: Hi, Bob!In this example:
- The greet function has two parameters, name and greeting, each with default values (“Guest” and “Hello”, respectively).
- You can call greet() without any arguments, and it will use the default values.
- You can also provide one or both arguments to override the default values.
Get Vadi Bu’s stories in your inbox
Join Medium for free to get updates from this writer.
Mixing Default and Non-Default Parameters
If a function has parameters with and without default values, parameters with default values should come after those without default values to avoid ambiguity.
func displayMessage(_ message: String, repeatCount: Int = 1) {
for _ in 0..<repeatCount {
print(message)
}
}
displayMessage("Swift is awesome!")
// Uses default repeatCount of 1
// Output: Swift is awesome!
displayMessage("Swift is awesome!", repeatCount: 3)
// Overrides repeatCount
// Output:
// Swift is awesome!
// Swift is awesome!
// Swift is awesome!Benefits of Default Parameters
- Flexibility. Allows you to call a function with various numbers of arguments.
- Simplifies Code. Reduces the need to overload functions just to accommodate different numbers of parameters.
- Readability. Makes function calls cleaner by avoiding passing values for parameters that often remain constant.
Conclusion
Default parameters in Swift provide a convenient way to define flexible and reusable functions. By allowing parameters to have default values, you can create functions that are easier to call and reduce code duplication.








