Default Parameter Values
A default parameter value is a fallback value a function uses automatically if you don't provide one yourself.
In this page:
Declaring a Default Value
A parameter can be given a default value using = value, making it optional for callers to specify.
Example: Declaring a Default Value
func greet(name: String, greeting: String = "Hello") -> String {
return "\(greeting), \(name)!"
}
print(greet(name: "Sam"))
print(greet(name: "Sam", greeting: "Hi"))
Login to try C/C++/Java/PHP code in the editor
Multiple Defaults
A function can have several parameters with default values, and callers only need to override the ones they care about.
Example: Multiple Defaults
func makeCoffee(size: String = "medium", sugar: Int = 1) -> String {
return "A \(size) coffee with \(sugar) sugar(s)"
}
print(makeCoffee())
print(makeCoffee(size: "large"))
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Placing a parameter with a default value before required parameters in a way that makes calls confusing; Swift allows it but convention favors defaults last.
- Assuming a default value is recomputed for every call in some special way; it's just a normal expression evaluated at the call site if omitted.
- Forgetting that once you provide any value for a defaulted parameter, you must still use its argument label unless it's also
_.
Chapter Summary
- A parameter can specify a default value with
= valueafter its type. - Callers can omit a defaulted parameter, and the default is used automatically.
- Defaults reduce the need for multiple overloaded versions of a function.
- Non-default parameters are usually listed before default ones by convention.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: