Lesson 12Control Flow
If-Else
Two Paths: If-Else
Sometimes you want to do one thing if a condition is true, and something else if it's false. That's where else comes in!
Basic Syntax
if condition {
// runs if true
} else {
// runs if false
}How It Works
✓
Condition is TRUE
Code inside if block runs
✗
Condition is FALSE
Code inside else block runs
Real-World Examples
🎮
If lives > 0, keep playing. Else, game over!
🔐
If password correct, login. Else, show error!
☀️
If sunny, go outside. Else, stay inside!
Key Points
- Only ONE block runs - never both!
- The
elseblock is optional - Use curly braces
{ }for each block
main.swift
// Basic if-else
let age = 15
if age >= 18 {
print("You are an adult")
} else {
print("You are a minor")
}
// Checking a boolean
let isLoggedIn = false
if isLoggedIn {
print("Welcome back!")
} else {
print("Please log in")
}
// Number comparison
let score = 45
if score >= 60 {
print("You passed!")
} else {
print("Keep practicing!")
}
// String comparison
let password = "secret123"
let userInput = "secret123"
if password == userInput {
print("Access granted!")
} else {
print("Wrong password!")
}
// Checking if number is even or odd
let number = 7
if number % 2 == 0 {
print("\(number) is even")
} else {
print("\(number) is odd")
}
// Real game example
var lives = 0
if lives > 0 {
print("Keep playing!")
} else {
print("Game Over!")
}Try It Yourself!
Write an if-else statement that checks if a number is positive or negative and prints the appropriate message!