Functions
Function Argument Labels and Parameter Names¶
Each function parameter has both an argument label and a parameter name. The argument label is used when calling the function; each argument is written in the function call with its argument label before it. The parameter name is used in the implementation of the function. By default, parameters use their parameter name as their argument label.
- func someFunction(firstParameterName: Int, secondParameterName: Int) {
- // In the function body, firstParameterName and secondParameterName
- // refer to the argument values for the first and second parameters.
- }
- someFunction(firstParameterName: 1, secondParameterName: 2)
All parameters must have unique names. Although it’s possible for multiple parameters to have the same argument label, unique argument labels help make your code more readable.
Specifying Argument Labels¶
You write an argument label before the parameter name, separated by a space:
- func someFunction(argumentLabel parameterName: Int) {
- // In the function body, parameterName refers to the argument value
- // for that parameter.
- }
Here’s a variation of the greet(person:) function that takes a person’s name and hometown and returns a greeting:
- func greet(person: String, from hometown: String) -> String {
- return "Hello \(person)! Glad you could visit from \(hometown)."
- }
- print(greet(person: "Bill", from: "Cupertino"))
- // Prints "Hello Bill! Glad you could visit from Cupertino."
The use of argument labels can allow a function to be called in an expressive, sentence-like manner, while still providing a function body that’s readable and clear in intent.
Omitting Argument Labels¶
If you don’t want an argument label for a parameter, write an underscore (_) instead of an explicit argument label for that parameter.
- func someFunction(_ firstParameterName: Int, secondParameterName: Int) {
- // In the function body, firstParameterName and secondParameterName
- // refer to the argument values for the first and second parameters.
- }
- someFunction(1, secondParameterName: 2)
If a parameter has an argument label, the argument must be labeled when you call the function.