Swift Introduction | Functions | External Argument Names
An argument can have an external name in addition to the parameter variable name. Write it as follows.
(externalName variableName:Type)
The external name identifies the argument when calling the function. Consider this example.
func tax(price p:Int, rate r:Double) -> Int {
return Int(Double(p) * (1.0 + r))
}
var res:Int = tax(price:10000, rate:0.08)
The tax function calculates and returns a price including tax from a price and tax rate. Its arguments are defined as follows.
tax(price p:Int, rate r:Double)
The parameter names are p and r, which are used inside the function. The call uses the external names.
tax(price: 10000, rate: 0.08)
Using price and rate makes the role of each argument clear. Without external names, the call looks like this.
tax(10000, 0.08)
External names make calls with multiple arguments easier to understand and help reduce mistakes.
Shorthand
Writing both an external name and a variable name can be cumbersome. You can use the variable name as the external name.
func tax(price:Int, rate:Double) -> Int {
return Int(Double(price) * (1.0 + rate))
}
var res:Int = tax(10000, rate:0.08)
This shorthand keeps the source code concise and readable because the external name and the variable name are the same.