Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 146 ยท Functions and Closures

Argument Labels and Parameter Names

Understand Swift argument labels and parameter names, the underscore, default values, variadic parameters and inout, and learn how labels make function calls read like clear sentences.

Take a look at this call from the standard library: numbers.firstIndex(of: 7). It reads almost like English: "first index of 7". Now imagine it was numbers.firstIndex(7). You would have to guess what the 7 means. Swift keeps that readability through argument labels, words that appear in the call and tell the reader the role of each argument.

This lesson explains the two names every parameter can have, how to remove or change them, and then three related features: default values, variadic parameters and inout parameters. It builds on Functions and leads to Function Types.

Two names for every parameter

Each parameter can have an argument label (used by the caller) and a parameter name (used inside the function body). If you write just one name, it is used for both. If you write two, the first is the label.

Swift Labels and names

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

In move(from start: Int, to end: Int), the caller writes from: and to:, while the body uses start and end. Each side gets the name that suits it. The call reads as a phrase, "move from 3 to 9", and the body reads as plain variables. In volume, one name serves both purposes.

A good habit is to design the call site first. Write the call as you wish to read it, then choose labels and names that make it work. Swift's API Design Guidelines say the same thing: clarity at the point of use is the most important goal.

Omitting a label with an underscore

Sometimes the label adds noise. If the function name already says what the argument is, you can drop the label by writing an underscore _ as the label.

Swift The underscore label

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first argument of a function often has no label when it is the main subject, as in print("Hello") or square(7). Labels on the later arguments describe their roles ("to: 0...100"). A useful rule is: when the first argument forms a grammatical phrase with the name of the function, omit its label. append(5) reads fine; removeAll(keepingCapacity: true) needs the label.

Omitting labels is an API design decision, not just a shortcut. If every parameter is unlabeled, as in add(3, 4, 5, 6), the call becomes cryptic as soon as the types are the same. Keep labels when they prevent mix-ups.

Labels are part of the function's identity

The full name of a function includes its labels. move(from:to:) and move(to:from:) are different functions, and so are send(_:to:) and send(_:from:). That is why Swift allows overloads that differ only in labels, and why calling a function with the wrong labels is an error rather than a silent bug.

Swift Wrong or missing label (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler reports error: missing argument labels 'from:to:' in call and offers to insert them. Calling with the labels in the wrong order is rejected too: error: argument 'from' must precede argument 'to' (the labels must appear in the declared order). This strictness prevents a class of bugs common in other languages, where two Int parameters can be swapped without any warning.

Default parameter values

Give a parameter a value in the declaration, and callers may leave it out. Defaults keep common calls short while leaving all options available.

Swift Default values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

(import Foundation is needed because rounded() links against the C math library on Linux.) When there are several defaults, callers can skip any of them and keep the others in order. Notice connect(host: "intranet", secure: false), which skips port. This is one of the real advantages of labels: they make skipping unambiguous.

Put parameters without defaults first, and defaults at the end. Defaults are evaluated each time the function is called, so a default can be any expression, such as Date() or [].

A default value replaces an entire family of overloads. Without defaults you would write a one-argument function, a two-argument function and a three-argument function that all do the same thing. In Swift one declaration is enough.

Variadic parameters

A variadic parameter accepts zero or more values of the same type. Write ... after the type. Inside the function it appears as an array.

Swift Variadic parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

numbers has the type [Double] inside the function, so you can use count, isEmpty, loops and everything else. The standard print function is variadic: print("a", "b", "c").

Two limits apply. First, you cannot pass an existing array directly to a variadic parameter: average(list) fails with error: cannot pass array of type '[Double]' as variadic arguments of type 'Double', and you must either spread the elements by hand or add an overload that takes [Double]. (Swift has no "spread" operator.) Second, a function can have several variadic parameters since Swift 5.4, but the parameter that follows one needs a label so that the call stays unambiguous.

inout parameters

Normally a function receives a copy of its arguments and cannot change the caller's variables. For value types such as Int, String, arrays and structs that is exactly what you want. When a function should modify the caller's variable, mark the parameter inout and pass the argument with an ampersand &.

Swift inout parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The & at the call site is intentional: it warns the reader that the variable may change. How does it work? Swift copies the value in, lets the function modify the copy and copies it back when the function returns. (The optimizer often avoids the copies, but the semantics are copy-in, copy-out.) You can only pass a var; passing a let or a literal is an error:

Swift inout needs a variable (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler says error: cannot pass immutable value as inout argument: 'counter' is a 'let' constant. Change let to var and it compiles.

Do not pass the same variable twice to a function with two inout parameters, as in swapValues(&x, &x). Swift enforces exclusive access: overlapping writes to one variable are rejected at compile time when it can see them (error: inout arguments are not allowed to alias each other), and trap at runtime otherwise. The same rule is why swap(&array[0], &array[1]) fails with overlapping accesses to 'array' and the compiler suggests swapAt(_:_:), the right tool.

Putting it together: designing a good signature

Compare these two versions of the same function:

Swift Designing a call site

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The second version can be called with just a message and a recipient, and the optional details are named when they matter. Anyone reading send("server down", to: "ops", urgent: true, retries: 5) understands it without looking up the declaration.

Pitfalls and guidelines

  • Do not drop all labels just to type less. Keep a label when two arguments share a type or when the role is not obvious.
  • Label defaults (decimals: Int = 2) always. A defaulted parameter without a label almost always reads badly.
  • Avoid long parameter lists. More than four parameters, even with defaults, suggests a struct that groups related options.
  • Prefer returning a value to inout. inout is right for in-place algorithms like swapAt or sort, but a function returning the new value is easier to test and reason about.
  • Mind the order: required parameters first, defaults last, variadics near the end.
  • Label and parameter names are checked at compile time and cost nothing at run time.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In func move(from start: Int, to end: Int), how do you call the function?

    The first name is the argument label used by the caller; the second is the name used inside the body. The labels must be written in the declared order.
  2. 2. What does the underscore in func square(_ number: Int) do?

    An underscore in the label position means the caller passes the argument without a label.
  3. 3. Inside func average(_ numbers: Double...), what is the type of numbers?

    A variadic parameter is available inside the function as an array of the declared type.
  4. 4. How do you pass a variable to an inout parameter?

    The ampersand marks the argument as modifiable. A let constant or a literal cannot be passed as inout.
  5. 5. Why do default parameter values reduce the number of overloads you need?

    With defaults, one declaration handles calls with some or all of the optional arguments, replacing a family of overloads.

Summary

  • Each parameter can have an argument label (for the caller) and a parameter name (for the body): func move(from start: Int, to end: Int).
  • Use _ to remove a label when the function name already explains the argument.
  • Labels are part of a function's name; missing or misordered labels are compile errors.
  • Default values (port: Int = 443) let callers skip arguments and replace families of overloads.
  • A variadic parameter (Double...) becomes an array in the body; you cannot pass an array to it directly.
  • inout plus & lets a function modify the caller's variable; it needs a var and obeys exclusive access.
  • Design the call site first, so that it reads like a clear phrase.

Next: Function Types