</>
Skip to content
Swift lessons (12/33)

Swift — If Else

Basic if

let temperature = 28

if temperature > 25 {
    print("It's warm!")
}

if-else

let hour = 14

if hour < 12 {
    print("Good morning!")
} else {
    print("Good afternoon!")
}

if-else if-else

let score = 85

if score >= 90 {
    print("Grade: A")
} else if score >= 80 {
    print("Grade: B")
} else if score >= 70 {
    print("Grade: C")
} else {
    print("Grade: F")
}

switch statement

let day = 3

switch day {
case 1:
    print("Monday")
case 2:
    print("Tuesday")
case 3:
    print("Wednesday")
case 6, 7:
    print("Weekend!")
default:
    print("Invalid day")
}

switch with patterns

let value = 42

switch value {
case 0:
    print("Zero")
case 1...9:
    print("Single digit")
case 10...99:
    print("Double digit")
default:
    print("Large number")
}

// Tuple matching
let point = (1, 1)

switch point {
case (0, 0):
    print("Origin")
case (_, 0):
    print("On x-axis")
case (0, _):
    print("On y-axis")
case (-2...2, -2...2):
    print("Inside 2x2 box")
default:
    print("Outside")
}

guard statement

func process(name: String?) {
    guard let name = name else {
        print("No name")
        return
    }
    print("Processing: \(name)")
}

process(name: "Alice") // Processing: Alice
process(name: nil)     // No name

Combining conditions

let age = 25
let income = 50000

if age >= 18 && income >= 30000 {
    print("Qualifies for premium")
}

if age < 12 || age > 65 {
    print("Discounted ticket")
}

Mini Practice

Write Swift code that:

  1. Uses switch with ranges
  2. Pattern matches a tuple
  3. Uses guard for early return
  4. Combines conditions with && and ||

Up Next

In the next lesson, you'll learn about Switch — Swift's powerful switch statement.

Related Topics

Frequently Asked Questions about If Else

What is If Else in Swift?

If Else is a fundamental concept in Swift. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn If Else?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn If Else.

Why is If Else important in Swift?

If Else is essential for Swift development. Understanding this concept will help you write better code and solve real-world problems more effectively.