Swift functions with external parameters
Function Parameter Names
Function parameters have both an external parameter name and a local parameter name. An external parameter name is used to label arguments passed to a function call. A local parameter name is used in the implementation of the function.
func someFunction(firstParameterName: Int, secondParameterName: Int) {
// function body goes here
// firstParameterName and secondParameterName refer to
// the argument values for the first and second parameters
}
someFunction(1, secondParameterName: 2)
By default, the first parameter omits its external name, and the second and subsequent parameters use their local name as their external name. All parameters must have unique local names, but may share external parameter in common.
Specifying External Parameter Names
You write an external parameter name before the local parameter name it supports, separated by a space:
func someFunction(externalParameterName localParameterName: Int) {
// function body goes here, and can use localParameterName
// to refer to the argument value for that parameter
}
NOTE
If you provide an external parameter name for a parameter, that external name must always be used when you call the function.
Here’s a version of the sayHello(_:)
function that takes the names of two people and returns a greeting for both of them:
func sayHello(to person: String, and anotherPerson: String) -> String {
return "Hello \(person) and \(anotherPerson)!"
}
print(sayHello(to: "Bill", and: "Ted"))
// prints "Hello Bill and Ted!"
By specifying external parameter names for both parameters, both the first and second arguments to thesayHello(to:and:)
function must be labeled when you call it.
The use of external parameter names can allow a function to be called in an expressive, sentence-like manner, while still providing a function body that is readable and clear in intent.
Omitting External Parameter Names
If you do not want to use an external name for the second or subsequent parameters of a function, write an underscore (_
) instead of an explicit external name for that parameter.
func someFunction(firstParameterName: Int, _ secondParameterName: Int) {
// function body goes here
// firstParameterName and secondParameterName refer to
// the argument values for the first and second parameters
}
someFunction(1, 2)
NOTE
Because the first parameter omits its external parameter name by default, explicitly writing an underscore is extraneous.
Default Parameter Values
You can define a default value for any parameter in a function by assigning a value to the parameter after that parameter’s type. If a default value is defined, you can omit that parameter when calling the function.
func someFunction(parameterWithDefault: Int = 12) {
// function body goes here
// if no arguments are passed to the function call,
// value of parameterWithDefault is 42
}
someFunction(6) // parameterWithDefault is 6
someFunction() // parameterWithDefault is 12