AnDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
if expression in Swift is a control flow construct that evaluates a boolean condition and directly yields a value from the executed branch. Introduced in Swift 5.9, it allows if constructs to be parsed and evaluated as expressions rather than statements, enabling their direct use in variable assignments, return statements, and property initializers without mutating state or relying on the ternary operator (?:).
Core Mechanics and Compiler Rules
To be evaluated as an expression rather than a statement, theif construct must adhere to strict compiler rules regarding exhaustiveness, branch composition, and type resolution.
1. Exhaustiveness Requirement
Unlike an if statement, an if expression must guarantee that a value is produced regardless of the evaluation path. Syntactically, Swift strictly requires an else branch for an if expression. Without an else branch, the compiler parses the construct as a statement rather than an expression. This makes it invalid on the right side of an assignment or return, even if the expected return type of the expression is Void.
2. Single-Expression Branches
Each branch within the if expression must contain exactly one expression. The compiler implicitly returns the result of this single expression. If a branch contains multiple statements (such as logging or intermediate variable declarations), the compiler cannot infer the yield value, and the construct reverts to being treated as a standard if statement.
if expression. By default, the single expression in every branch must evaluate to the exact same type.
Never Type
If a branch evaluates to the Never type (for example, by calling fatalError() or throwing an error), the compiler successfully ignores that branch for type resolution. The expression’s unified type is inferred entirely from the remaining valid branches.
Usage Contexts
The compiler recognizes anif expression in three specific syntactic positions:
- Assignment: On the right-hand side of a
=operator (letorvardeclarations). - Return: Directly following a
returnkeyword in a function or closure. - Implicit Return: As the sole expression in a single-expression function, closure, or computed property.
Master Swift with Deep Grasping Methodology!Learn More





