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:
Syntax
func functionName(param: Type = defaultValue) {
// body
}
functionName()
functionName(param: value)
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
// Define the function `greet` taking `name`, `greeting` and returning a String
func greet(name: String, greeting: String = "Hello") -> String {
// Return `"\(greeting), \(name)!"` from this function
return "\(greeting), \(name)!"
}
// Print `greet(name: "Sam")` to the console
print(greet(name: "Sam"))
// Print `greet(name: "Sam", greeting: "Hi")` to the console
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
// Define the function `makeCoffee` taking `size`, `sugar` and returning a String
func makeCoffee(size: String = "medium", sugar: Int = 1) -> String {
// Return `"A \(size) coffee with \(sugar) sugar(s)"` from this function
return "A \(size) coffee with \(sugar) sugar(s)"
}
// Print `makeCoffee()` to the console
print(makeCoffee())
// Print `makeCoffee(size: "large")` to the console
print(makeCoffee(size: "large"))
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
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: