skip to content

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%

answer

  1. each branch checked on its own
  2. Int literal meets Double literal
  3. context from an annotation or as
  4. one expression per branch
  5. no return out of a branch

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.

solid answer

~50 s

Since Swift 5.9 (SE-0380), `if` and `switch` can be used as expressions, under rules that keep type checking fast and local. Each branch is type-checked independently and all must produce the same type, so `if retrying { 0 } else { 1.5 }` fails with "branches have mismatching types 'Int' and 'Double'"; the fix is context - `let delay: Double = ...`, `0 as Double`, or a function's return type. The ternary differs: `retrying ? 0 : 1.5` infers `Double`. Each branch must be a single expression, a `throw`, or a single call that never returns; an `if` needs an unconditional `else`; a `nil` branch needs a contextual type. The expression may only initialize a variable, be assigned, be returned, be thrown, or form a branch of another such expression - not be passed as an argument - and `return`, `break` or `continue` cannot jump out of a branch.

code

swift · 17 lines
swift
enum Tier { case free, pro, team }

func monthlyPrice(for tier: Tier, seats: Int) -> Double {
    switch tier {          // switch expression, implicit return
    case .free: 0           // the return type makes these literals Double
    case .pro: 12
    case .team: Double(seats) * 9.5
    }
}

let retrying = Bool.random()
let delay: Double = if retrying { 0 } else { 1.5 }   // annotation supplies the type
let backoff = if retrying { 0 as Double } else { 1.5 } // or an as cast in a branch
let ternary = retrying ? 0 : 1.5                       // ternary infers Double

print(monthlyPrice(for: .team, seats: 4))  // 38.0
print(type(of: delay), type(of: backoff), type(of: ternary))  // Double Double Double

go deeper

for a junior

Recall that since Swift 5.9 if and switch can initialize a constant, and that every if used this way needs an else.

for a middle

Explain the positions where an if or switch expression is allowed and why each branch must be a single expression.

for a senior

Diagnose the mismatching-branch-types error from independent type checking, and choose between an annotation, an as cast, the ternary and the statement form.

for a principal

There is no team-level decision here beyond style; a lead might standardise on expressions for simple value selection and statements once branches need side effects.

## What changed in Swift 5.9 Before Swift 5.9, `if` and `switch` were statements only. Producing a value from them meant declaring an uninitialized `let` and assigning it in every branch, or writing an immediately-called closure. **SE-0380, implemented in Swift 5.9**, made both usable as **expressions** in a few positions: ```swift let label = if isPremium { "Pro" } else { "Free" } func monthlyPrice(for tier: Tier, seats: Int) -> Double { switch tier { case .free: 0 case .pro: 12 case .team: Double(seats) * 9.5 } } ``` The second example shows a related detail: a function or closure whose body is a single `if` or `switch` expression can drop the `return` keyword. The reference manual calls these **conditional expressions**. ## Independent type checking - why the example fails The central rule is that **each branch is type-checked on its own**, and all branches must produce the **same type**. Nothing flows between branches. In ```swift let delay = if retrying { 0 } else { 1.5 } ``` the literal `0` checked alone defaults to `Int`, and `1.5` alone defaults to `Double`. The Swift 6.4 compiler rejects the declaration: ```plaintext error: branches have mismatching types 'Int' and 'Double' ``` The fix is to give the branches a type from outside, which the reference manual recommends: - annotate the variable: `let delay: Double = if retrying { 0 } else { 1.5 }`; - cast inside a branch: `if retrying { 0 as Double } else { 1.5 }`; - rely on existing context, as `monthlyPrice` does: the declared return type `Double` makes the literals `0` and `12` into `Double` values. The same rule explains why `let x = if p { nil } else { 2.0 }` fails with "'nil' requires a contextual type" and works as `let x: Double? = ...`. | Form | `0` and `1.5` without an annotation | |---|---| | Ternary `retrying ? 0 : 1.5` | compiles; both results are solved together and the type is `Double` | | `if retrying { 0 } else { 1.5 }` as an expression | error: branches have mismatching types 'Int' and 'Double' | The proposal explains the asymmetry: full two-way inference across many branches would slow the type checker and make each branch harder to reason about on its own, so SE-0380 chose independent checking and asks for an annotation in the ambiguous cases. ## The structural rules 1. **One expression per branch.** A branch is a single expression whose value becomes the result. Logging a line before the value fails with "non-expression branch of 'if' expression may only end with a 'throw'". 2. **A branch may throw or end the program instead.** A branch that is a `throw`, or a single call to a `Never`-returning function such as `fatalError(_:)`, produces no value and is exempt from the type match; the remaining branches decide the type. Only a branch that ends in `throw` may run other statements first: the Swift 6.4 compiler rejects `if p { print("a"); fatalError("x") } else { 1 }` with the same "may only end with a 'throw'" error, although SE-0380's text suggested a terminating call would be allowed there too. 3. **Every `if` needs a final unconditional `else`.** Without it: "'if' must have an unconditional 'else' to be used as expression". A `switch` expression must already be exhaustive, as any `switch` must. 4. **No jumps out of a branch.** `return`, `break` and `continue` cannot leave from inside an expression branch: "cannot use 'return' to transfer control out of 'if' expression". An earlier draft of the proposal allowed `return` and the accepted version removed it. ## Where the expression may appear The reference manual lists the positions: - the initial value of a variable or constant declaration; - the value assigned to an existing variable; - the value returned from a function, closure or property getter, with or without `return`; - the error in a `throw`; - a branch of another conditional expression. Anywhere else - as a function argument, or as an operand such as `(if p { 1 } else { 2 }) + 1` - fails with "'if' may only be used as expression in return, throw, or as the source of an assignment". Inside a result builder, a bare `if` or `switch` is still a statement that the builder transforms; only one used as a variable's initial value is an expression. ## Review guidance - Use an `if` or `switch` expression for a value chosen from a few cases; it replaces declaring `let x: T` and assigning it in every branch, and puts the value next to its declaration. - When a branch needs a second statement, go back to the statement form; do not cram side effects into a call just to satisfy the one-expression rule. - Prefer an explicit annotation over `as` casts sprinkled in branches when literals of different kinds meet.

  • Can one branch of an if expression call fatalError while the other returns a value?
    Yes. A branch that is a single call to a `Never`-returning function such as `fatalError(_:)` produces no value, so it is exempt from the same-type rule, and the other branches decide the type: `let port = if let p { p } else { fatalError("no port") }` gives an `Int`. Only a branch ending in `throw` may run statements before it; the Swift 6.4 compiler rejects a log line before `fatalError` there.
  • Why can't you pass an if expression directly as a function argument?
    SE-0380 deliberately limited conditional expressions to declarations, assignments, returns, throws and nested branches, leaving general sub-expression positions as a future direction. The compiler rejects other positions with "'if' may only be used as expression in return, throw, or as the source of an assignment". Bind the value to a `let` first, or use the ternary operator for a two-way choice.

  • An if expression finds a common type across its branches, like the ternary
  • An if expression may omit else when the result is optional
  • A branch can log a line before producing its value
  • You can return early from inside an if expression branch
  • An if expression can be passed straight into a function call