0Pricing
Swift Academy · Lesson

Defaults in Function Parameters

Give parameters default values to simplify call sites.

What Are Default Parameters

A function parameter can have a default value. Callers may omit that argument, and Swift fills in the default automatically.

func greet(name: String = "Guest") {
    print("Hello, \(name)")
}
greet()
greet(name: "Ada")

Declaring a Default

You assign a default after the parameter type using =. The default is used only when the caller does not pass that argument.

func power(base: Int, exponent: Int = 2) -> Int {
    var result = 1
    for _ in 0..<exponent { result *= base }
    return result
}
print(power(base: 5))
print(power(base: 5, exponent: 3))

All lessons in this course

  1. The Nil-Coalescing Operator
  2. Chaining Default Values
  3. Defaults in Function Parameters
  4. Dictionary Default Subscripts
← Back to Swift Academy