Logic in Swift
Control flow in Swift is designed to be safe and expressive. While it includes familiar constructs like if and while, it introduces powerful improvements like mandatory braces for all blocks (no single-line if statements without {}) and a switch statement that doesn't 'fall through' by default. As an Engineering Manager, you'll find these constraints significantly reduce common logic bugs in native code.
- Conditional Statements: if and guard
Swift uses if for standard branching. However, for a Technical Lead, the guard statement is a game-changer. It is used to exit a function early if a condition isn't met, keeping the 'happy path' of your code flat and readable rather than nested in multiple if-else blocks.
- The Exhaustive Switch
In Swift, switch statements must be exhaustive. If you are switching over an Enum (like a Project Status), you must handle every single case. This prevents you from accidentally forgetting to handle a new state after a refactor. Unlike Dart, you don't need break at the end of each case; the execution stops automatically after a match.
- Loops and Range Operators
Swift's for-in loop is the primary way to iterate. It works seamlessly with Ranges, which allow you to define a start and end point easily.
- Closed Range (1...5): Includes both 1 and 5 (loops 5 times).
- Half-Open Range (1..<5): Includes 1 but stops before 5 (loops 4 times).
- Stride: Used for non-sequential increments (e.g., counting by 2s).
Control Flow Comparison
| Feature | Swift | Dart (Flutter) |
|---|---|---|
| if parenthetical | Optional: if score > 10 | Required: if (score > 10) |
| Switch Fallthrough | Disabled by default | Enabled (requires break) |
| Switch Exhaustiveness | Mandatory | Optional (for non-enums) |
| Early Exit | guard statement | if (!condition) return |
| Ranges | Native: 1...5 | Custom or manual loops |