Swift Introduction | Functions | Default Argument Values

There are additional features to learn about function arguments. This article explains default values.

You can specify a default value for a function argument in advance. Assign a value to the argument variable with an equals sign (=), as shown below.

func functionName(argumentName:Type = defaultValue)

When you specify a default value, the argument name automatically becomes an external name that can be provided by the caller. There is no need to add a hash sign (#) as a shorthand declaration.

Specifying a default value means that the argument can be omitted. When calling the function, the argument may or may not be present. To make it clear which argument is being passed, an argument with a default value uses an external name.

The following example uses a default value.

func tax(#price:Int, rate:Double = 0.08) -> Int {
    return Int(Double(price) * (1.0 + rate))
}
 
var res:Int = tax(price:10000, rate:0.08)
var res3:Int = tax(price:12300)

If you omit the rate argument, Swift automatically uses 0.08.