Default Parameter Value in Swift example
Default Parameter Value in Swift
In Swift, default parameter values allow a function parameter to have a pre-defined value if no argument is provided for that parameter when the function is called. This enhances flexibility by allowing simpler function calls in common scenarios while still providing the option to customize behavior when needed.
func greet(person: String, greeting: String = "Hello") {
print("\(greeting), \(person)!")
}
// Calling the function without specifying the 'greeting' parameter
greet(person: "Alice") // Output: Hello, Alice!
// Calling the function and overriding the default 'greeting'
greet(person: "Bob", greeting: "Hi") // Output: Hi, Bob!
Where
- The greeting parameter has a default value of “Hello“.
- When greet(person: “Alice“) is called, the greeting parameter automatically uses its default value.
- When greet(person: “Bob“, greeting: “Hi“) is called, the provided argument “Hi” overrides the default value.