Swift Control Flow: Directing Your Code's Path
Control flow statements are the traffic signals of your code. They use keywords like `if`, `for`, and `switch` to make decisions and repeat actions, rather than just running top-to-bottom. This is how you show a list of items or check if a user is logged.
WHY IT EXISTS Without control flow, a program would be a simple, linear script that runs once from top to bottom and then stops. Control flow gives programs the ability to make decisions, repeat actions, and react differently to various inputs, which is essential for any non-trivial application.
THE MENTAL MODEL Think of control flow as a recipe's instructions. A simple recipe might say "mix flour, then add eggs." A more complex one says "IF the dough is too dry, add water" or "WHILE the oven is preheating, chop the vegetables." These conditional instructions and loops are what control flow provides to your code.
HOW IT WORKS Swift offers several ways to manage control flow. Conditional statements like if and guard execute code only if a certain condition is true. guard is particularly useful for exiting a function early if requirements aren't met, which avoids deeply nested if statements. Loops, such as for-in and while, repeat a block of code. for-in is used to iterate over a sequence like an array. switch statements compare a value against multiple possible patterns. Unlike in other languages, Swift's switch is exhaustive, meaning you must cover all possible cases, which prevents many common bugs.
WHEN TO USE IT Control flow is fundamental and used everywhere. Use if for simple binary decisions. Use guard at the beginning of a function to validate inputs. Use a for-in loop to process every item in a collection. Use a switch statement when you have a variable that can have several distinct states, especially with enums.
WHEN NOT TO USE IT Avoid creating complex, deeply nested if/else if/else chains. These are often a sign that you should refactor your code, perhaps by using a switch statement or breaking the logic into smaller functions. Swift's switch must be exhaustive, so it's a safer choice for handling all states of a variable.
ONE CANONICAL EXAMPLE A common use case is handling different user account types with an enum. Imagine an enum UserStatus with cases for active, inactive, and suspended. A switch statement on a user's status can cleanly run different logic for each case: show the main app for .active, a login prompt for .inactive, and an account locked message for .suspended. The compiler guarantees you've written code to handle all three possibilities.
Read the original → docs.swift.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.