skip to content

Syntax and Control Flow

The everyday surface of the language: let and var, operators and ranges, guard, switch and loops. Interviewers open here to see guard-first code and constants by default.

on this pageshow

explore

questions

18

In Swift, what is the difference between let and var, and why do Swift teams declare with let by default?

level: juniorimportance: must knowfreq 82%

answer

  1. one assignment versus many
  2. the compiler checks every write
  3. a warning about an unmutated var
  4. a let may be assigned later, once

basics

~20 s

let binds a name to a value exactly once and the compiler rejects any later assignment; var allows reassignment. Teams default to let because it states intent and the compiler warns when a local var is never mutated.

solid answer

~40 s

`let` declares a constant: once it has a value, any assignment to it is a compile-time error (`cannot assign to value: 'taxRate' is a 'let' constant`). `var` declares a variable that can be reassigned. Swift code uses `let` unless the value really changes, and the compiler backs the habit up: a local `var` that is never written after its declaration draws the warning `variable 'taxRate' was never mutated; consider changing to 'let' constant`. A local `let` does not need its value on the declaration line: `let fee: Double` can be assigned later, as long as definite initialization proves it is assigned exactly once on every path before it is read. One limit to remember: `let` freezes the binding, so a constant holding a class instance still lets you change that object's `var` properties.

code

swift · 11 lines
swift
func printReceipt() {
    let orderID = "A-1042"        // never reassigned: let
    var subtotal = 0.0            // grows as lines are added: var
    let prices = [4.5, 12.0, 3.25]
    for price in prices {
        subtotal += price
    }
    var taxRate = 0.08            // never reassigned, but declared var
    print(orderID, subtotal * (1 + taxRate))
}
printReceipt()

go deeper

for a junior

Recall that let is assigned once and var can change, and that writing to a let is a compile-time error. Mention defaulting to let and changing to var only when needed.

for a middle

Explain the never-mutated warning, why it targets local variables, and how a local let can be assigned later under definite initialization, quoting both errors it can produce.

for a senior

Show you use the warnings as review signals: a never-mutated var hints at a forgotten update, and a deferred let documents that every branch must decide the value exactly once.

for a principal

Frame let-by-default as a team convention the compiler already enforces for locals, and know where it stops: globals and stored properties still need reviewers, and let on a class reference freezes only the reference.

## Two kinds of named value Swift has two declarations for a named stored value: - **`let`** introduces a **constant**. After it has been given a value, that value can never be replaced. - **`var`** introduces a **variable**. It can be assigned a new value as often as the code needs. Both are typed at compile time, both can take a type annotation (`let orderID: String = "A-1042"`) or let the compiler infer the type, and both can be declared at global scope, inside a function, or as a property of a type. The core difference between them is whether the name may be **re-assigned**. | | `let` | `var` | |---|---|---| | Can be reassigned | No, compile-time error | Yes | | Value on the declaration line | Optional for a local; required for a global in an ordinary source file | Same rule as `let` | | Compiler nudge | None needed | Warning if a local is never mutated | | Typical use | IDs, configuration, intermediate results | Accumulators, loop state, counters | ## What the compiler enforces The check is entirely **static**: nothing happens at run time, because a program that writes to a `let` never compiles. Assigning to a constant produces: ``` error: cannot assign to value: 'taxRate' is a 'let' constant note: change 'let' to 'var' to make it mutable ``` The same rule covers **function parameters**, which are constants by default: `total = total.rounded()` inside a function whose parameter is `total` fails with the same `is a 'let' constant` error. ## The "never mutated" warning The reverse mistake, a `var` that never changes, is not an error but the compiler notices it. For a **local** variable that is written once at its declaration and only read afterwards, Swift 6.4 reports: ``` warning: variable 'taxRate' was never mutated; consider changing to 'let' constant ``` That warning is a large part of why Swift codebases read as `let`-first. Reviewers treat it as a signal: either the value really is constant and should say so, or the author meant to update it somewhere and forgot. A global `var` or a stored `var` property that nobody writes gets no such warning, because code elsewhere in the module could write it. The compiler has a separate warning for a value that is never **read** at all, `initialization of variable 'unused' was never used; consider replacing with assignment to '_' or removing it`; don't confuse the two. ## Declaring a constant now, assigning it later A local `let` may be declared **without** a value and assigned later. The compiler then runs **definite initialization**: it proves that, on every path, the constant is assigned **exactly once** before anything reads it. 1. Declare the constant with a type annotation, because there is no literal to infer from: `let fee: Double`. 2. Assign it in every branch of an `if`/`else` chain or a `switch`. 3. Read it only after the branches join. If one branch forgets the assignment, the read fails with `constant 'fee' used before being initialized`. If a path assigns twice, for example inside a loop, the compiler reports `immutable value 'fee' may only be initialized once`. The analysis is conservative: when you know a value is always set but the compiler cannot prove it, simplify the branches or fall back to `var`. This deferred form is for locals. A global constant in an ordinary source file must have its value on the declaration line; without one the compiler reports `global 'let' declaration requires an initializer expression`. ## What let does not freeze `let` makes the **binding** constant, not necessarily everything reachable through it. A constant that holds a **class instance** cannot be pointed at a different object, but the object's own `var` properties can still change. A constant that holds a **struct** behaves differently, because a struct is a value. Those rules are covered with value and reference types; for this question it is enough to say that `let` freezes the name's value, whatever kind of value that is. ## Why let by default is the team rule - **Intent**: a reader of a checkout function sees at once which values are fixed (the order ID, the tax rate) and which accumulate (the subtotal). - **Fewer bugs**: an accidental reassignment of a constant is caught at compile time instead of in a code review or a crash report. - **Free tooling**: the never-mutated warning turns the rule into something the compiler checks, so nobody has to police it by hand. - **Easy to relax**: changing `let` to `var` is a one-word edit, and the compiler's note suggests exactly that when you really need mutation.

  • Can a local let in Swift be declared without a value, and what does the compiler require?
    Yes. Write `let fee: Double` with an annotation and assign it later. Definite initialization must prove it is assigned exactly once on every path before the first read; a missing branch gives `constant 'fee' used before being initialized`, and assigning twice, as in a loop, gives `immutable value 'fee' may only be initialized once`. A global constant in a library file has no such option: it needs an initializer expression.
  • Does Swift warn about a global var or a stored var property that is never reassigned?
    No. The `was never mutated` warning targets local variables, whose every use the compiler can see in one function body. A global `var` or a stored `var` property might be written from another file or another type, so the compiler stays silent and the `let` decision is left to the author and the reviewer.
  • Why does assigning to a function parameter fail in Swift, and what is the usual fix?
    Function parameters are constants, so `total = total.rounded()` fails with `cannot assign to value: 'total' is a 'let' constant`. Declare a local instead, often with the same name: `let total = total.rounded()`. Changing the caller's variable is a different feature, an `inout` parameter, covered with function parameters.

  • Saying let makes a class instance's properties immutable too
  • Believing a let must always get its value on the declaration line
  • Treating let as a style hint the compiler never checks
  • Thinking a deferred let can be assigned in each loop iteration
  • Declaring everything var because the compiler never comments on it
open as a page

In Swift, how does type inference choose a type for a literal, and when must you write a type annotation instead?

level: juniorimportance: must knowfreq 68%

basics

~20 s

A Swift literal has no type of its own: the compiler takes one from context, such as an annotation or the other operands, else defaults to Int, Double, String or Bool. Annotate when that default is wrong or nothing can be inferred.

open as a page

In Swift, how does a guard statement differ from an if statement, and why must guard's else branch exit the enclosing scope?

level: juniorimportance: must knowfreq 78%

basics

~20 s

A guard runs its else branch when its condition fails, and that branch must leave the enclosing scope through return, break, continue, throw or a call that never returns. Values the condition binds stay usable for the rest of the scope.

open as a page

In Swift, how do the closed range `a...b`, the half-open range `a..<b` and one-sided ranges like `items[2...]` differ, and when does a range trap?

level: juniorimportance: must knowfreq 70%

basics

~20 s

a...b is a ClosedRange including b; a..<b is a Range stopping before b, so a..<a is empty. One-sided forms like items[2...] take the missing bound from the collection. Inverted bounds trap, as does slicing past an array's indices.

open as a page

In Swift, when does a defer block run, and in what order do several defer blocks in the same scope execute?

level: middleimportance: must knowfreq 60%

basics

~20 s

A defer block runs when control leaves the scope it was declared in, by return, break, continue, a thrown error or reaching the closing brace. Several defer blocks in one scope run in reverse order: the last one written runs first.

open as a page

A game's Int32 score counter crashes after a very long session; what does Swift do on integer overflow, and when is `&+` the right fix?

level: middleimportance: must knowfreq 66%

basics

~20 s

Swift's +, - and * trap at run time on overflow, and the compiler rejects overflows it can compute. &+, &- and &* wrap in two's complement: right for hashes and checksums, wrong for a score, which should clamp or use a wider type.

open as a page

Swift has no C-style for loop, so how do you write counted, stepped, filtered and run-at-least-once loops instead?

level: juniorimportance: should knowfreq 50%

basics

~20 s

Swift loops with for-in over a sequence: a range to count, stride(from:to:by:) or stride(from:through:by:) to step, and a where clause to skip passes. while checks before each pass; repeat-while checks after, so its body runs at least once.

open as a page

Why does Swift reject `if count { … }` for an Int and `1 < x < 10`, and how do `&&` and `?:` evaluate?

level: juniorimportance: should knowfreq 45%

basics

~20 s

A Swift boolean condition must be a Bool, and comparison operators are non-associative, so if count and 1 < x < 10 are rejected. && and || skip the right operand once the left decides; ?: evaluates one branch, and both branches share a type.

open as a page

In Swift, why does interpolating an optional into a string literal produce a warning, and how do you print a fallback instead?

level: middleimportance: should knowfreq 45%

basics

~20 s

Interpolating an Optional prints its debug form, nil or Optional(120), which is almost never meant for output, so Swift warns. Unwrap it, use ?? with a same-type fallback, or since Swift 6.2 write (value, default: "text").

open as a page

In Swift, when may a declaration reuse a name from an outer scope, and when does the compiler reject the redeclaration?

level: middleimportance: should knowfreq 38%

basics

~20 s

An inner scope may shadow a global, a parameter or an outer local of the same name; declaring a name twice in one scope is an error, invalid redeclaration. Shadowing is legal but can hide which value a line reads.

open as a page

In Swift, why does a switch case never run into the next case by default, and what exactly does the fallthrough keyword do?

level: middleimportance: should knowfreq 40%

basics

~20 s

A Swift switch ends as soon as the first matching case body finishes, so no break is needed. fallthrough opts in: control jumps straight into the next case's body without checking that case's pattern or where clause.

open as a page

In Swift, how do you leave an inner and an outer loop at once, and what does an unlabeled break inside a switch end?

level: middleimportance: should knowfreq 45%

basics

~20 s

Label the outer loop and write break with that label to leave every nested loop at once. An unlabeled break ends only the innermost loop or switch, so in a switch inside a loop the loop carries on.

open as a page

In Swift, what does `%` return for a negative operand such as `-7 % 3`, and why does `%` not compile on a Double?

level: middleimportance: should knowfreq 35%

basics

~20 s

Swift's % is a remainder, not a modulo: the result takes the left operand's sign, so -7 % 3 is -1, and the divisor's sign is ignored. Double has no %; use truncatingRemainder(dividingBy:) or the IEEE remainder(dividingBy:).

open as a page

In a Swift executable, when does a global constant's initializer run, and why can reading a main.swift top-level constant from another file go wrong?

level: seniorimportance: should knowfreq 28%

basics

~20 s

A global declared in an ordinary source file is initialized lazily, exactly once, on first access. main.swift's top-level code instead runs in statement order, so another file reading one of its constants before that line executes sees uninitialized storage.

open as a page

Since Swift 5.9 lets if and switch produce values, why does `let delay = if retrying { 0 } else { 1.5 }` fail to compile, and what rules apply?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Swift type-checks each branch of an if or switch expression on its own, so 0 becomes Int and 1.5 becomes Double, and the compiler reports mismatching branch types. Supplying the type, as in let delay: Double, fixes it.

open as a page

A teammate wants `+` on a Swift `Vector2D` struct and a new `•` dot-product operator; how is each declared, and what does a `precedencegroup` decide?

level: seniorimportance: should knowfreq 28%

basics

~20 s

Overloading + needs only a static func + on Vector2D, which keeps AdditionPrecedence. A new • needs a file-scope infix operator declaration naming a precedencegroup, which fixes how tightly it binds against other groups and how a run of it associates.

open as a page

In Swift, how do backtick identifiers work, and what did Swift 6.2's raw identifiers add to them?

level: seniorimportance: nice to knowfreq 18%

basics

~20 s

Backticks let a keyword such as default serve as a name. Since Swift 6.2 (SE-0451) they also form raw identifiers containing spaces, punctuation or a leading digit, such as descriptive test names, which must be backticked at every use.

open as a page

As the lead of a shared Swift codebase, would you allow custom operators, and what rule would you write for when one is acceptable?

level: principalimportance: nice to knowfreq 20%

basics

~20 s

Allow overloading standard operators where the meaning carries over, such as + on vectors or == through Equatable, and keep brand-new operators rare: only for a domain with established notation, each with a named method, an explicit precedencegroup and one owning module.

open as a page