skip to content

In Swift, how do you label and destructure a tuple such as a file transfer's progress, and when should it become a struct instead?

level: juniorimportance: should knowfreq 45%

answer

  1. a compound value with no declaration
  2. labels are part of the type
  3. let (a, _) = pair
  4. no protocol conformances at all
  5. == and < stop at six elements

basics

~20 s

A Swift tuple groups values into one unnamed type, optionally labeled as (sent: Int64, total: Int64), and let (sent, total) = progress destructures it. Promote it to a struct once it needs Hashable or Codable, methods, or storage.

solid answer

~40 s

A tuple like `(sent: 0, total: 4_096)` is a value type with no declaration: you read elements by label (`progress.sent`) or position (`progress.0`), destructure with `let (sent, total) = progress`, and skip parts with `_`. Labels belong to the type; a labeled tuple converts to and from the unlabeled `(Int64, Int64)`, but not to a tuple with different labels. A `typealias` only names the shape. The limits decide when to switch: a tuple cannot conform to any protocol, so it cannot be a `Set` element, a `Dictionary` key or `Codable`, and it cannot carry methods. The standard library's `==` and `<` for tuples are free functions that stop at six elements. Keep tuples for short-lived local groupings; make anything stored, shared across an API or persisted a struct.

code

swift · 15 lines
swift
typealias TransferProgress = (sent: Int64, total: Int64)

var progress: TransferProgress = (sent: 0, total: 4_096)
progress.sent += 1_024

let (sent, total) = progress          // destructuring
print(sent, total, progress.0)        // 1024 4096 1024

let unlabeled: (Int64, Int64) = progress
let relabeled: TransferProgress = unlabeled
print(relabeled == progress)          // true: == exists for 2 to 6 Equatable elements
print((1, "b") < (1, "c"))            // true: compared from the left

let (done, _) = progress              // skip an element with _
print(done)                           // 1024

go deeper

for a junior

Know how to build a labeled tuple, read it by label or position, and destructure it with let and an underscore for the parts you skip.

for a middle

Explain why tuples cannot be Set elements, dictionary keys or Codable, and that their == and < are free functions limited to six elements.

for a senior

Spot tuples that have quietly become stored model data and argue for a struct with synthesized conformances before they spread across an API.

for a principal

Treat tuple versus struct as an API-surface question: a named type is the unit you can document, extend and evolve; a tuple is a local convenience.

## What a tuple is in Swift A **tuple** groups several values into one compound value without declaring a type for it. `(404, "Not Found")` has the type `(Int, String)`; the elements may be of any types and need not match each other. A tuple is a **value type**: assigning it or passing it to a function copies every element, exactly as a struct would (a class instance inside is copied as a reference to the same object), so reassigning an element in one copy never affects the other. Tuples suit values that belong together for a moment, such as a file transfer's progress: - `let progress = (sent: 1_024, total: 4_096)` creates a tuple with **labels** `sent` and `total`; - `progress.sent` and `progress.0` read the same element, by label or by zero-based position; - `var` makes every element mutable: `progress.sent += 512` is legal on a `var` tuple. ## Labels, positions and destructuring **Destructuring** unpacks a tuple into separate constants in one statement: `let (sent, total) = progress`. An underscore skips elements you do not need: `let (sent, _) = progress`. The same pattern works in a `for` loop over an array of tuples and in a `switch` case. Labels are part of the tuple's type, and the compiler checks them: - a labeled tuple converts to the unlabeled tuple with the same element types, and back again, so `let raw: (Int64, Int64) = progress` compiles; - a tuple with **different** labels does not convert: assigning `(a: 1, b: 2)` to a variable of type `(sent: Int, total: Int)` fails with "cannot convert value of type '(a: Int, b: Int)' to specified type '(sent: Int, total: Int)'"; - an unlabeled literal fills a labeled tuple by position, so `(0, 4_096)` assigned to `(sent: Int64, total: Int64)` sets `sent` to 0; keep the order consistent or write the labels. ## typealias names the shape `typealias TransferProgress = (sent: Int64, total: Int64)` gives the tuple type a readable name. A **type alias** is only another name for an existing type: values move freely between `TransferProgress` and `(sent: Int64, total: Int64)`, and the alias adds no methods, conformances or checks. That is also why a type alias cannot fix any of the limits below. ## What a tuple cannot do A tuple is a **structural type**: it has no declaration, so nothing can be attached to it. In practice: | Need | Tuple | Struct | |---|---|---| | Conform to `Equatable`, `Hashable`, `Codable` or your own protocol | No | Yes, often synthesized | | Be a `Set` element or a `Dictionary` key | No | Yes, once `Hashable` | | Methods, computed properties, extensions | No (tuple extensions are still experimental) | Yes | | Compare with `==` and `<` | Only up to six elements, via free functions | Through its conformances | | Doc comments and access control per member | No | Yes | The comparison row deserves a closer look. The standard library declares **free functions** `==` and `!=` for tuples of two to six `Equatable` elements, and `<`, `<=`, `>`, `>=` for tuples of two to six `Comparable` elements, comparing element by element from the left. They make `(1, "b") < (1, "c")` work, but they are overloads, not a conformance: a tuple still fails a generic constraint such as `T: Equatable`, so `firstIndex(of:)` on an array of tuples does not compile, and a seven-element tuple has no `==` at all. ## When to promote a tuple to a struct 1. The value is **stored** in a property, a collection or a cache rather than used and discarded within a few lines. 2. It needs **any protocol conformance**: `Hashable` for a `Set` or a dictionary key, `Codable` for persistence, `Identifiable` for a list. 3. It needs **behaviour**: a computed `fractionComplete`, a validation rule, a method. 4. It crosses an **API boundary** where a named type documents intent better than a label pair. A struct costs a few lines and gives a memberwise initializer, synthesized conformances and a place for behaviour. A tuple costs nothing and is ideal for a local grouping, a destructured pair in a loop, or a short-lived intermediate value. Returning several values from a function is the other classic tuple use; that pattern belongs with function parameters and return types.

  • Why does `(1, 2) == (1, 2)` compile in Swift when a tuple cannot conform to Equatable?
    The standard library declares free `==` and `!=` overloads generic over tuples of two to six `Equatable` elements, and `<`, `<=`, `>`, `>=` for `Comparable` ones. They are functions, not a conformance, so a seven-element tuple has no `==`, and a tuple still fails a generic `T: Equatable` constraint, which is why `firstIndex(of:)` on an array of tuples does not compile.
  • Can you assign `(a: 1, b: 2)` to a variable of type `(sent: Int, total: Int)`?
    No. The compiler reports "cannot convert value of type '(a: Int, b: Int)' to specified type '(sent: Int, total: Int)'". Labels can be added to or dropped from an unlabeled tuple with the same element types, but one set of labels is not converted into a different one.

  • Tuple labels are just comments, so any two-Int tuple converts to any other.
  • A tuple is Hashable whenever its elements are, so it works as a Set element.
  • A typealias for a tuple creates a distinct type with its own checks.
  • Passing a tuple to a function shares it, like passing an object.
  • The == operator works on tuples of any length.