Argument Labels
func functionName(label name: Type) { } // custom label
func functionName(_ name: Type) { } // no label
functionName(label: value)
functionName(value)
Default Argument Labels
By default, calling a function requires using each parameter's name as a label, which makes the call self-documenting.
Example: Default Argument Labels
// Define the function `multiply` taking `x`, `y` and returning an Int
func multiply(x: Int, y: Int) -> Int {
// Return `x * y` from this function
return x * y
}
// Print `multiply(x: 6, y: 7)` to the console
print(multiply(x: 6, y: 7))
Login to try C/C++/Java/PHP code in the editor
Custom External Labels
You can give a parameter a different label for callers than the name used inside the function body, improving readability at the call site.
person is what callers type, while name is used inside the function body.Example: Custom External Labels
// Define the function `greet` taking `name` and returning a String
func greet(person name: String) -> String {
// Return `"Hello, \(name)"` from this function
return "Hello, \(name)"
}
// Print `greet(person: "Alice")` to the console
print(greet(person: "Alice"))
Login to try C/C++/Java/PHP code in the editor
Omitting Labels with Underscore
Using an underscore _ as the external label allows the function to be called without naming that particular argument.
Example: Omitting Labels with Underscore
// Define the function `square` taking `number` and returning an Int
func square(_ number: Int) -> Int {
// Return `number * number` from this function
return number * number
}
// Print `square(5)` to the console
print(square(5))
Login to try C/C++/Java/PHP code in the editor
- Confusing the argument label (used at the call site) with the parameter name (used inside the function body) -- they can be different words.
- Forgetting that using
_as the label removes the requirement to write a label at all when calling. - Assuming all Swift functions require labels; the first parameter's label is often omitted by convention when it reads naturally without one.
- By default, a parameter's name serves as both its external label and internal name.
- You can specify a different external label before the internal name:
func f(externalLabel internalName: Type). - Using
_as the external label lets the function be called without naming that argument. - Good argument labels make call sites read like natural English.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: