skip to content

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%

answer

  1. one compound return value
  2. access by label or position
  3. unused result means a warning
  4. attribute on the declaration
  5. underscore assignment at the call

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.

solid answer

~40 s

A Swift function returns several values by declaring a **tuple** return type, `-> (id: Int, queuedCount: Int)`. Callers read `receipt.id` or `receipt.0`, or destructure with `let (id, _) = outbox.send(...)`. An optional tuple, `(min: Int, max: Int)?`, says the whole pair may be missing, which differs from a tuple of optionals. Separately, calling a function that returns a non-`Void` value and dropping the result makes the compiler warn `result of call to 'pending()' is unused`. Marking the declaration `@discardableResult` suppresses that warning for every call site, which suits functions whose main job is a side effect and whose result is incidental: `Set.insert(_:)` returns `(inserted: Bool, memberAfterInsert: Element)` and carries the attribute. For a result that usually matters, leave the warning on and let the rare caller write `_ = f()`.

code

swift · 21 lines
swift
struct Outbox {
    private(set) var queued: [String] = []

    @discardableResult
    mutating func send(_ text: String, to recipient: String) -> (id: Int, queuedCount: Int) {
        queued.append("\(recipient): \(text)")
        return (id: queued.count, queuedCount: queued.count)
    }

    func pending() -> Int { queued.count }
}

var outbox = Outbox()
outbox.send("hi", to: "alice")               // no warning: @discardableResult
let receipt = outbox.send("yo", to: "bob")
print(receipt.id, receipt.queuedCount, receipt.0)
let (id, _) = outbox.send("hey", to: "carol")
print(id)

outbox.pending()                             // warning: result of call to 'pending()' is unused
_ = outbox.pending()                         // explicit discard, no warning

go deeper

for a junior

Recall the syntax: a tuple return type with labels, reading by label or index, and _ = to ignore a result on purpose.

for a middle

Explain where the unused-result warning comes from, what @discardableResult changes, and why the standard library puts it on insert and remove methods.

for a senior

Judge when a result is incidental enough to be discardable and when a tuple return should become a struct before it spreads through a codebase.

for a principal

For an SDK, the attribute is a statement about how much the result matters; keep it off results that report failures callers must handle.

## Returning several values with a tuple Swift lets a function return one **compound value** whose type is a tuple. Naming the elements in the return type makes the call site self-describing: ```swift func send(_ text: String, to recipient: String) -> (id: Int, queuedCount: Int) { // ... return (id: 42, queuedCount: 3) } let receipt = send("hi", to: "bob") print(receipt.id, receipt.queuedCount) // by label print(receipt.0) // by position let (id, _) = send("yo", to: "amy") // destructure, ignore one element ``` Points worth knowing: - **Labels come from the declaration.** The body can return an unlabelled `(42, 3)`; the caller still sees the labels of the declared return type. - **Optional tuple versus tuple of optionals.** `-> (min: Int, max: Int)?` says the whole result may be absent, so the caller unwraps once with `if let bounds = minMax(values)`. `-> (min: Int?, max: Int?)` says each element may be missing independently. Choose the one that matches reality: an empty input has neither a minimum nor a maximum, so the first is right for that case. - **When to stop using a tuple.** A tuple cannot declare methods or conformances of its own, and its exact shape spreads to every call site. Once the result has several fields, is stored, or crosses a module boundary, a small `struct` is usually clearer. ## The unused-result warning Swift treats a dropped return value as a likely bug. Calling a function that returns a non-`Void` value as a bare statement produces a warning: ```plaintext warning: result of call to 'pending()' is unused ``` The warning catches a classic mistake: calling a method that *returns* a modified copy, such as `sorted()`, and expecting it to change the original. There are two ways to silence it: 1. **At the call site**, with an explicit discard: `_ = outbox.pending()`. This documents that this particular caller chose to ignore the value. 2. **At the declaration**, with `@discardableResult`. The attribute applies to a function or method declaration and suppresses the warning for every caller. ## When `@discardableResult` is the right choice The attribute fits functions whose **side effect is the point** and whose result is a by-product some callers want and most do not. The standard library uses it exactly that way: | API | Result | Why it is discardable | |---|---|---| | `Set.insert(_:)` | `(inserted: Bool, memberAfterInsert: Element)` | most callers just want the element in the set | | `Dictionary.updateValue(_:forKey:)` | the old value, `Value?` | the update is the point; the old value is optional information | | `Array.remove(at:)` | the removed element | many callers only want it gone | | `removeFirst()` on a range-replaceable collection | the removed element | same reasoning | It is the wrong choice when ignoring the result is almost always a bug. A function that returns a new value instead of mutating, a validation result, or a status that signals failure should keep the warning, so a caller who drops it gets told. ## Designing the messaging SDK call For `send(_:to:)` returning a receipt tuple: - If most callers fire and forget, and the receipt is for the few that track delivery, mark it `@discardableResult`. - If the receipt carries a failure that callers must check, leave the attribute off so the warning nudges every caller to look. - If the receipt grows past two or three fields, replace the tuple with a `Receipt` struct: adding a field to a struct leaves existing callers compiling, while adding an element to a returned tuple breaks every caller that destructures it. ## Edge cases - A `Void` function never warns, because there is no result to ignore. - Optional chaining does not hide the warning: `outbox?.pending()` as a statement still warns, while a `@discardableResult` method called the same way does not. - Ignoring the result of a tuple-returning call is no different from any other result: the warning is about the whole return value, not its elements. - `@discardableResult` changes only the diagnostic; it does not change the type, the overloads or how the function is called. - The attribute goes on the declaration, so it cannot be applied by a caller who disagrees with the author; that caller uses `_ =` instead.

  • In Swift, when should a function return an optional tuple rather than a tuple of optionals?
    Return `(min: Int, max: Int)?` when the elements are either all present or all absent, as with the minimum and maximum of a possibly empty array: the caller unwraps once. Use `(min: Int?, max: Int?)` only when each element can be missing on its own. The first form makes the impossible state, a minimum without a maximum, unrepresentable.
  • Why does Set.insert(_:) return a tuple marked @discardableResult instead of returning Void?
    Most callers only want the element in the set, so the attribute keeps their code warning-free. A caller that needs to know whether the element was new, or wants the existing equal member, reads `inserted` or `memberAfterInsert` from the returned tuple.

  • Ignoring any return value in Swift is a compile error
  • @discardableResult makes the function return Void to callers
  • Tuple elements can only be read by position, never by label
  • Every function with a return value should be marked @discardableResult
  • An optional tuple and a tuple of optionals mean the same thing