Argument Labels
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
func multiply(x: Int, y: Int) -> Int {
return x * y
}
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.
Note: Here person is what callers type, while name is used inside the function body.
Example: Custom External Labels
func greet(person name: String) -> String {
return "Hello, \(name)"
}
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
func square(_ number: Int) -> Int {
return number * number
}
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: