In Swift, you can provide default values for function and inittializers parameters. This allows you to call a function or init without explicitly passing arguments for every parameter. If a parameter is omitted in a function call, its default value will be used.
Defining Default Values
To assign a default value to a parameter, simply set the value when declaring the parameter in the function signature.
func greet(name: String = "Guest") {
print("Hello, \(name)!")
}
greet() // Output: "Hello, Guest!"
greet(name: "Alice") // Output: "Hello, Alice!"
In the example above, the greet()
function has a default value of "Guest" for the name
parameter. If no argument is provided, the default value will be used.
Multiple Default Values
You can provide default values for multiple parameters, making it flexible to call the function with or without arguments.
func printMessage(message: String = "Hello", times: Int = 1) {
for _ in 0..<times {
print(message)
}
}
printMessage() // Output: "Hello"
printMessage(message: "Hi") // Output: "Hi"
printMessage(times: 3) // Output: "Hello" (3 times)
Here, both message
and times
have default values, allowing for different combinations of arguments when calling printMessage()
.
Be the first to comment