← Back to Swift Course | Chapter 4: Functions | Lesson 3 of 7

Default Parameter Values

A default parameter value is a fallback value a function uses automatically if you don't provide one yourself.

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

markup
func greet(name: String, greeting: String = "Hello") -> String {
    return "\(greeting), \(name)!"
}
print(greet(name: "Sam"))
print(greet(name: "Sam", greeting: "Hi"))

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

markup
func makeCoffee(size: String = "medium", sugar: Int = 1) -> String {
    return "A \(size) coffee with \(sugar) sugar(s)"
}
print(makeCoffee())
print(makeCoffee(size: "large"))
Common Mistakes
  1. 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.
  2. 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.
  3. 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 = value after 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.