0
0
Swiftprogramming~10 mins

If and if-else statements in Swift - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - If and if-else statements
Start
Evaluate condition
Execute if-block
Continue
Check if else-block exists?
Execute else-block
Continue
Continue
The program checks a condition. If true, it runs the if-block. If false and else-block exists, it runs else-block. Then it continues.
Execution Sample
Swift
let number = 7
if number % 2 == 0 {
    print("Even")
} else {
    print("Odd")
}
Checks if number is even or odd and prints the result.
Execution Table
StepConditionResultBranch TakenOutput
1number % 2 == 07 % 2 == 0 → 1 == 0 → falseelse-blockOdd
2End of if-elseNo more conditionsExit
💡 Condition is false, else-block runs, then execution ends.
Variable Tracker
VariableStartAfter Step 1Final
number777
Key Moments - 2 Insights
Why does the else-block run when the condition is false?
Because the condition in the if statement is false (see execution_table step 1), the program skips the if-block and runs the else-block instead.
What happens if there is no else-block and the condition is false?
The program skips the if-block and continues without running any code inside the if or else blocks (not shown in this example).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the condition result at step 1?
Atrue
Bundefined
Cfalse
Derror
💡 Hint
Check the 'Result' column in execution_table row 1.
At which step does the else-block run?
AStep 1
BStep 2
CNo else-block runs
DBefore step 1
💡 Hint
Look at the 'Branch Taken' and 'Output' columns in execution_table row 1.
If number was 8, how would the output change?
A"Odd"
B"Even"
CNo output
DError
💡 Hint
Think about the condition number % 2 == 0 with number = 8.
Concept Snapshot
if condition {
  // code runs if condition is true
} else {
  // code runs if condition is false
}

- Condition is checked once.
- If true, if-block runs.
- Else-block runs only if condition is false.
- Else-block is optional.
Full Transcript
This visual shows how if and if-else statements work in Swift. The program starts by checking a condition. If the condition is true, it runs the code inside the if-block. If the condition is false and there is an else-block, it runs the else-block code instead. Then the program continues after the if-else. For example, checking if a number is even or odd uses this logic. The execution table shows the condition check, the branch taken, and the output printed. The variable tracker shows the value of the number throughout. Key moments clarify why the else-block runs when the condition is false and what happens if there is no else-block. The quiz asks about condition results, when the else-block runs, and how changing the number affects output. The snapshot summarizes the syntax and behavior simply.