Defining a parameter's default values
We can define default values for any parameter by using the equal to operator (=
) within the function definition when we declare the parameters. The following example shows how to declare a function with a parameter's default values:
func sayHello(name: String, greeting: String = "Bonjour") {
print("\(greeting) \(name)")
}
In the function declaration, we have defined one parameter without a default value (name:String)
and one parameter with a default value (greeting: String = "Bonjour")
. When a parameter has a default value declared, we can call the function with or without setting a value for that parameter. The following example shows how to call the sayHello()
function without setting the greeting
parameter, and also how to call it when you do set the greeting
parameter:
sayHello(name:"Jon")
sayHello(name:"Jon", greeting: "Hello")
In the sayHello(name...