skip to content

Functions and Closures

Functions with argument labels, defaults and inout, functions as values, and closures with capture lists. Interviewers ask about escaping closures because they decide memory behaviour.

on this pageshow

explore

questions

17

In Swift, how can a closure expression passed to a function be shortened, and how do trailing and multiple trailing closures change the call site?

level: juniorimportance: must knowfreq 70%

answer

  1. context supplies the types
  2. single expression returns itself
  3. $0, $1 by position
  4. outside the parentheses
  5. first unlabeled, the rest labeled

basics

~20 s

Swift infers a closure's parameter and return types from the call, so a single-expression closure can drop its types, return and parameter names ($0, $1). A final closure argument can move after the parentheses as a trailing closure.

solid answer

~50 s

The full form is `{ (lhs: Download, rhs: Download) -> Bool in return lhs.bytes > rhs.bytes }`. Because `sorted(by:)` already declares the function type it expects, Swift infers the parameter and return types, a single-expression body returns its value implicitly, and the names can become `$0` and `$1`, leaving `{ $0.bytes > $1.bytes }`. When the closure is the last argument it can be written after the parentheses as a trailing closure, and the parentheses disappear when it is the only argument: `finished.sorted { $0.bytes > $1.bytes }`. Since Swift 5.3 a call can take several trailing closures: the first is unlabeled and every later one carries its argument label, as in `download(url) { fraction in … } completion: { result in … }`. Shorthand names suit one-line bodies; a multi-line closure reads better with named parameters.

code

swift · 31 lines
swift
struct Download {
    let url: String
    let bytes: Int
}

func download(
    _ url: String,
    progress: ((Double) -> Void)? = nil,
    completion: @escaping (Download) -> Void
) {
    progress?(1.0)
    completion(Download(url: url, bytes: url.count * 1_000))
}

let finished = [Download(url: "a.png", bytes: 300), Download(url: "bb.png", bytes: 900)]

// The same comparison, shortened step by step.
let a = finished.sorted(by: { (lhs: Download, rhs: Download) -> Bool in return lhs.bytes > rhs.bytes })
let b = finished.sorted(by: { lhs, rhs in lhs.bytes > rhs.bytes })
let c = finished.sorted { $0.bytes > $1.bytes }
print(a[0].url, b[0].url, c[0].url)

// One trailing closure: the defaulted progress parameter is skipped, so it becomes completion.
download("cat.png") { result in print("saved", result.bytes) }

// Multiple trailing closures: the first is unlabeled, every later one carries its label.
download("dog.png") { fraction in
    print("progress", fraction)
} completion: { result in
    print("saved", result.bytes)
}

go deeper

for a junior

Recall the four shortenings in order: inferred types, implicit return, $0-style names, trailing syntax. Be able to rewrite a full closure into its shortest form and back.

for a middle

Explain that every shortening rests on the parameter's declared function type, and show the multiple-trailing-closure call shape with the first closure unlabeled and the rest labeled.

for a senior

Know how the forward scan picks the parameter for an unlabeled trailing closure, why defaulted closure parameters can bind differently in Swift 5 and Swift 6 modes, and how labeling fixes it.

for a principal

Treat trailing-closure friendliness as API design: order closure parameters so the forward scan lands on the obvious one, and set a team convention for when shorthand names stop being readable.

## The full closure expression A **closure expression** is an unnamed function written inline: `{ (parameters) -> ReturnType in statements }`. The keyword `in` separates the signature from the body. Writing everything out is always legal, but Swift lets you remove most of it whenever the surrounding call already says what the closure must look like. Take a list of finished image downloads sorted by size, largest first. `sorted(by:)` expects a function of type `(Element, Element) -> Bool`, so the compiler knows the parameter and return types before it reads your closure. ## Shortening a closure step by step 1. **Full form:** `finished.sorted(by: { (lhs: Download, rhs: Download) -> Bool in return lhs.bytes > rhs.bytes })`. 2. **Inferred types:** the context fixes both parameter types and the `Bool` result, so `{ lhs, rhs in return lhs.bytes > rhs.bytes }` is equivalent. 3. **Implicit return:** a closure whose body is a **single expression** returns that expression's value, so `return` can go: `{ lhs, rhs in lhs.bytes > rhs.bytes }`. 4. **Shorthand argument names:** parameters are also available positionally as `$0`, `$1`, `$2`, … When you use them and drop the names and types, you also drop `in`: `{ $0.bytes > $1.bytes }`. Some details matter in review: - Closure parameters are **constants**; to change one, copy it into a local `var` inside the body. - Implicit return applies to a single-expression body only. A body with two statements needs an explicit `return`; otherwise the compiler reports `missing return in closure expected to return 'Int'` (for an `Int` result). - If the omitted types cannot be inferred, compilation fails: every shortening relies on the context's function type. - A closure that has a **capture list** still needs `in`, even when it uses `$0`. Passing an operator such as `>` directly as the comparison is a separate topic — functions and operators as values, covered with first-class callables. ## Trailing closures When a closure is the **final argument**, you may write it after the call's closing parenthesis. This is a **trailing closure**: still an argument, just written outside. - The first trailing closure is written **without its argument label**. - If the closure is the only argument, the empty parentheses can be dropped too: `finished.sorted { $0.bytes > $1.bytes }`. - Trailing syntax pays off when the body spans several lines, as completion handlers usually do. ## Multiple trailing closures and the forward scan Since **Swift 5.3** (SE-0279) a call can end with several trailing closures. The first stays unlabeled; each later one is written with its argument label: ```swift download("dog.png") { fraction in print("progress", fraction) } completion: { result in print("saved", result.bytes) } ``` Which parameter receives the **unlabeled** closure is decided by the **forward scan** (SE-0286): the compiler walks the parameters left to right and gives it to the next parameter whose type is a function type, or a function type wrapped in `Optional`. A heuristic skips a parameter that has a default value when a later parameter still needs an argument. That is why `download("cat.png") { result in … }` binds to `completion` even though the defaulted `progress` parameter comes first. | Call | Swift 5 language mode | Swift 6 language mode | |---|---|---| | `download("a") { … }` with defaulted `progress`, required `completion` | binds `completion` | binds `completion` | | `notify { … }` where `onSuccess` and `onFailure` are both defaulted closures | binds `onFailure` (old backward match) with a warning | binds `onSuccess` | In Swift 5 mode the compiler still falls back to the older backward match when it and the forward scan disagree, and warns: `backward matching of the unlabeled trailing closure is deprecated; label the argument with 'onFailure' to suppress this warning`. Swift 6 mode matches forward only. Labeling the argument removes the ambiguity in both. ## A Swift 6.4 addition Swift 6.4 (SE-0508) lets a trailing closure follow an array type in an expression, so `[String] { … }` calls an `Array` initializer that takes a closure. Earlier releases did not treat that closure as part of the expression, so such code failed to compile. ## Readability guidelines - Use `$0` in one-line closures where the meaning is obvious; name parameters once the body grows. - Prefer trailing syntax for the last, longest closure; label every closure when an API takes several defaulted ones.

  • In Swift, why does `download("cat.png") { result in … }` bind to `completion` when a defaulted `progress` closure parameter comes first?
    The forward scan would offer the unlabeled trailing closure to `progress` first, but a heuristic skips a parameter that has a default value when a later parameter, here `completion`, still requires an argument. So `progress` keeps its `nil` default and the closure becomes `completion`, in both Swift 5 and Swift 6 language modes.
  • In Swift, why can the same trailing-closure call bind to different parameters in Swift 5 and Swift 6 language modes?
    When two defaulted closure parameters could both take the unlabeled closure, Swift 5 mode keeps the pre-5.3 backward match, scanning from the last parameter, and warns that backward matching is deprecated. Swift 6 mode uses only the forward scan, so the first parameter wins. Writing the label, such as `onFailure:`, makes the call mean the same in both modes.
  • In Swift, when does a closure that uses `$0` still have to write `in`?
    When it has a capture list. `{ [weak self] in self?.apply($0) }` must keep `in` to end the capture list, even though the parameters are named positionally. Without a capture list, using `$0` and dropping names and types means dropping `in` as well.

  • A trailing closure is a different kind of value from a closure in parentheses.
  • Every trailing closure after the first is also written without its label.
  • A single-expression closure still needs an explicit return keyword.
  • An unlabeled trailing closure always binds to the function's last parameter.
  • Shorthand $0 and $1 names make long multi-line closures easier to review.

Assumes Swift 6.4: multiple trailing closures date from Swift 5.3, Swift 5 mode still falls back to backward matching with a warning while Swift 6 mode matches forward only, and trailing closures after an array type arrived in 6.4.

open as a page

In Swift, how do you store validation functions such as isNotEmpty in a dictionary of rules, and what type does each entry have?

level: juniorimportance: must knowfreq 60%

basics

~20 s

A Swift function is a value with a function type such as (String) -> Bool. Naming it without parentheses, isNotEmpty rather than isNotEmpty(), yields the function itself, so it can sit in a [String: (String) -> Bool] dictionary, be passed or be returned.

open as a page

In Swift, what is the difference between a parameter's argument label and its parameter name, and what does writing _ change at the call site?

level: juniorimportance: must knowfreq 72%

basics

~20 s

A Swift argument label is the word callers write before an argument; the parameter name is what the function body uses. The label defaults to the name, a separate word overrides it, and _ removes it.

open as a page

In Swift, why must an image downloader's completion-handler parameter be marked @escaping, and why are closure parameters non-escaping by default?

level: middleimportance: must knowfreq 72%

basics

~20 s

A closure escapes when it is stored or called after the function returns, as a completion handler is, so Swift requires @escaping on that parameter. Non-escaping is the default because the compiler can then guarantee the closure's lifetime ends with the call.

open as a page

In Swift, what do [weak self] and [unowned self] do in a download's completion handler when the screen closes before it finishes?

level: middleimportance: must knowfreq 82%

basics

~20 s

[weak self] captures an optional reference that becomes nil once the screen is deallocated, so the handler unwraps it and returns early. [unowned self] captures a non-optional reference assumed to be alive; reading it after deallocation traps.

open as a page

What does Swift's inout do to the caller's variable, and why must the call site write & before the argument?

level: middleimportance: must knowfreq 68%

basics

~20 s

Swift parameters are constants. Marking one inout lets the function assign to it, and the final value is written back to the caller's variable on return; the caller must pass a var prefixed with &.

open as a page

In a Swift networking helper, when should a retry policy be a stored property of function type rather than a protocol with one method?

level: middleimportance: should knowfreq 40%

basics

~20 s

Use a stored function property when the policy is one behaviour with ad hoc variants and test stubs. Use a protocol when it needs several requirements, visible state, or conformances such as Equatable or Codable, which function types cannot have.

open as a page

Why does a Swift function value lose its argument labels, and how do you reference one specific overload by name?

level: middleimportance: should knowfreq 30%

basics

~20 s

Argument labels are part of a Swift function's name, not its type, so hasMinimumLength(_:of:) yields a (String, Int) -> Bool called without labels. Pick one overload by its full name when labels differ, or by a type annotation when only types differ.

open as a page

In Swift, what does a nested function capture from its enclosing function, and what happens when the enclosing function returns it?

level: middleimportance: should knowfreq 45%

basics

~20 s

A Swift nested function captures the enclosing function's parameters and locals it uses. Returned, it keeps those variables alive; each call of the enclosing function creates fresh ones, while copies of one returned function share them.

open as a page

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%

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.

open as a page

How does a Swift function return several values as a labeled tuple, and what does @discardableResult change when a caller ignores the result?

level: middleimportance: should knowfreq 38%

basics

~20 s

A Swift function can return a tuple type such as (id: Int, queuedCount: Int), read by label or position or destructured. Ignoring any non-Void result draws an unused-result warning; @discardableResult on the declaration suppresses it for every caller.

open as a page

In Swift, why does a retry handler that uses `attempt` see a later reassignment while `{ [attempt] in … }` does not, and what does a capture list not copy?

level: seniorimportance: should knowfreq 50%

basics

~20 s

A closure captures the variable attempt itself and reads its current value when it runs. The capture-list entry [attempt] is a new constant initialised when the closure is created; for a class instance it copies only the reference, not the object.

open as a page

In Swift, what does the unapplied reference LengthRule.check produce, and how does it differ from the bound reference rule.check?

level: seniorimportance: should knowfreq 30%

basics

~20 s

LengthRule.check is a curried (LengthRule) -> (String) -> Bool: pass an instance, get the method. rule.check is a (String) -> Bool bound to its receiver, holding a copy of a struct or a strong reference to a class instance.

open as a page

A Swift property with a didSet observer is passed inout to a function that increments it three times. How many times does didSet fire, and why?

level: seniorimportance: should knowfreq 32%

basics

~20 s

Once. Swift's inout is copy-in copy-out: the property's value is read when the call starts, the function mutates a temporary copy, and the final value is assigned back once when it returns, so the setter and didSet run a single time.

open as a page

Why does Swift report ambiguous use of 'parse' when two parse(_:) overloads differ only in return type, and how do you resolve it?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Swift resolves overloads by labels, argument types and the expected return type. Two parse(_:) overloads differing only in return type both fit a call with no contextual type; a type annotation, an as coercion or a typed parameter resolves it.

open as a page

As a Swift team lead, would you mandate [weak self] in every escaping closure, ban it, or decide case by case, and how would you make the rule stick?

level: principalimportance: should knowfreq 35%

basics

~20 s

Decide by case under a written default: weak self when the work is pointless once the owner is gone or the owner holds the closure's storer; capture only the needed dependencies when work must finish; unowned only for structurally guaranteed lifetimes.

open as a page

In Swift, how does @autoclosure let ?? and assert(_:_:file:line:) skip evaluating an argument, and what makes it risky in your own APIs?

level: seniorimportance: nice to knowfreq 28%

basics

~20 s

@autoclosure wraps the argument expression in a parameterless closure, so the callee decides whether and when it runs: ?? evaluates its default only when the optional is nil, and assert evaluates its condition only in -Onone builds and playgrounds. Callers cannot see that deferral.

open as a page