skip to content

In Swift, when is a default parameter value evaluated, and what rules govern where defaulted and variadic parameters can sit in a signature?

level: middleimportance: should knowfreq 45%

answer

  1. evaluated per call, not once
  2. omitted arguments keep declared order
  3. defaults go last by convention
  4. variadic arrives as an array
  5. label after a variadic

basics

~20 s

A Swift default value is evaluated on every call that omits the argument. Labelled defaults can be skipped but never reordered; a variadic parameter takes zero or more values as an array, and the parameter after it needs a label.

solid answer

~40 s

A default value, `retries: Int = 3`, is an expression the compiler evaluates **at each call that omits the argument** — not once at declaration — so a default that calls a function runs it every time. Because arguments keep their declared order, any labelled defaulted parameter can be skipped, but the book advises putting defaulted parameters after the required ones so every call reads alike. A default cannot refer to another parameter. A **variadic** parameter, `_ recipients: User...`, accepts zero or more values and the body sees them as an array, `[User]`. You cannot pass an existing array to it, and since Swift 5.4 a function may have several variadic parameters as long as each parameter following one carries a label. Neither a default nor `...` combines with `inout`.

code

swift · 22 lines
swift
struct Message { let text: String }
struct User { let id: String }

func defaultRetries() -> Int {
    print("computing default")
    return 3
}

func send(_ message: Message, to recipient: User, retries: Int = defaultRetries()) {
    print("send '\(message.text)' to \(recipient.id), retries \(retries)")
}

func broadcast(_ messages: Message..., to recipients: User...) {
    print("\(messages.count) messages to \(recipients.count) users")
}

let alice = User(id: "alice")
send(Message(text: "a"), to: alice)              // computing default
send(Message(text: "b"), to: alice)              // computing default again
send(Message(text: "c"), to: alice, retries: 0)  // default not evaluated
broadcast(Message(text: "x"), Message(text: "y"), to: alice)
broadcast(to: alice)                              // zero messages

go deeper

for a junior

Recall the syntax: = value after the type for a default, three dots after the type for a variadic, and that the variadic arrives as an array.

for a middle

Explain that the default is evaluated at every call that omits it, that order stays fixed, and why an unlabelled default before a required parameter can never be skipped.

for a senior

Spot the costly default in review, design an array overload behind a variadic API, and know which combinations with inout the compiler rejects.

for a principal

For a shared SDK, adding a defaulted parameter keeps existing direct call sites compiling, which makes defaults the cheap way to grow an API without a new overload.

## Default parameter values A **default parameter value** is an expression written after the parameter's type: ```swift func send(_ message: Message, to recipient: User, retries: Int = 3) ``` Callers can then omit `retries:` entirely. Three rules govern how this behaves. ### 1. The expression runs at each call that omits the argument The reference manual is explicit: "The given expression is evaluated when the function is called." A default is not a constant captured once when the function is declared. If the default is `makeRetryPolicy()`, that function runs on every call that leaves the argument out, and does not run at all on a call that passes a value. ```swift func defaultRetries() -> Int { print("computing default") return 3 } func send(_ text: String, retries: Int = defaultRetries()) { } send("a") // prints "computing default" send("b") // prints it again send("c", retries: 0) // does not print ``` A special case: when the default is *exactly* a single macro such as `#line` or `#fileID`, it is evaluated at the **call site's** source location, which is how logging helpers report the caller's line. Wrap it in a larger expression and it is evaluated where the function is defined instead. ### 2. A default cannot read another parameter `func f(a: Int, b: Int = a)` does not compile; the compiler reports `cannot find 'a' in scope`. A default is evaluated in the caller's call, outside the function body, where the other parameters are not in scope. Compute such a fallback inside the body from an optional parameter instead. ### 3. Order is fixed, so placement matters Labels let a caller skip any defaulted parameter, but never reorder: `send("hi", retries: 1, to: user)` fails with `argument 'to' must precede argument 'retries'`. The book's guidance is to place parameters without defaults first, because they carry the function's meaning and the call then looks the same whether or not the trailing defaults are written. The guidance becomes a rule when labels are missing. With `func g(_ a: Int = 1, _ b: Int)`, the call `g(7)` binds `7` to `a` and then reports `missing argument for parameter #2 in call`: an unlabelled default ahead of an unlabelled required parameter can never be skipped. ## Variadic parameters A **variadic parameter** accepts zero or more values of one type, written with three dots after the type: ```swift func broadcast(_ messages: Message..., to recipients: User...) { // messages is [Message], recipients is [User] } broadcast(m1, m2, to: alice) broadcast(to: alice) // zero messages is allowed ``` Inside the body the parameter is an ordinary array (`Message...` is treated as `[Message]`). Things that surprise people: - **No array splatting.** Passing an existing `[Int]` to an `Int...` parameter fails: `cannot pass array of type '[Int]' as variadic arguments of type 'Int'`. The usual fix is to make the array-taking overload the real implementation and have the variadic one forward to it. - **Several variadics are allowed** since Swift 5.4, provided the parameter that follows each one has a label; otherwise the compiler reports `a parameter following a variadic parameter requires a label`. That label is what tells the compiler where one list ends. - **Zero arguments is valid**, so the body must handle an empty array. ## What does not combine | Combination | Result | |---|---| | `inout` with a default | error: `cannot provide default value to inout parameter` | | `inout` on a variadic | error: `'inout' must not be used on variadic parameters` | | Default that reads another parameter | error: the parameter is not in scope | | Several variadics, each followed by a label | allowed since Swift 5.4 | ## Defaults versus overloads Default values are how Swift avoids a family of near-identical overloads that only forward extra arguments. Compared with overloads they: - keep one implementation and one documentation comment; - let callers skip any labelled defaulted parameter, not only trailing ones; - are evaluated in the caller's call, so an expensive default is paid by every call that omits it. The last point is the one to watch in review: a default such as `Date()`, a freshly built configuration object or a lookup in shared state is re-evaluated each time, which is usually what you want for a timestamp and occasionally a surprise for anything costly.

  • How do you let callers pass either a list of values or an existing array to the same Swift API?
    Write the real implementation with an array parameter, `func broadcast(_ messages: [Message], to: User)`, and add a variadic overload that forwards: `func broadcast(_ messages: Message..., to user: User) { broadcast(messages, to: user) }`. Swift has no operator that spreads an array into a variadic parameter, so the array overload is the only way to accept one.
  • Why does a Swift logging helper declared with line: Int = #line report the caller's line rather than its own?
    When a default value is exactly one macro expression such as `#line` or `#fileID`, Swift evaluates it at the call site's source location. If the default were `#line + 0` or `(#line)`, it would be evaluated where the function is defined and every call would report the same line.

  • A default value is computed once when the function is declared
  • Labels let callers pass defaulted arguments in any order
  • A default value can be computed from an earlier parameter
  • You can pass an existing array straight into a variadic parameter
  • A function can have only one variadic parameter in current Swift