← 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.
Syntax
swift
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

markup
// 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"))

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
// 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"))
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
  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.