0
0
Swiftprogramming~3 mins

Why If and if-else statements in Swift? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your code could think and decide like you do in everyday choices?

The Scenario

Imagine you are sorting mail by hand, deciding which letters go to which person based on their address. You have to check each letter carefully and put it in the right pile.

The Problem

Doing this by hand is slow and easy to mess up. You might put a letter in the wrong pile or forget to check some letters. It takes a lot of time and focus.

The Solution

If and if-else statements let your program make decisions automatically. They check conditions and choose the right path, just like sorting mail quickly and correctly without mistakes.

Before vs After
Before
let score = 75
if score > 60 {
  print("Pass")
}
if score <= 60 {
  print("Fail")
}
After
let score = 75
if score > 60 {
  print("Pass")
} else {
  print("Fail")
}
What It Enables

This lets your programs react differently to different situations, making them smart and flexible.

Real Life Example

Think about a traffic light system that changes colors based on time or cars waiting. If-else statements help decide when to switch lights to keep traffic flowing smoothly.

Key Takeaways

If and if-else statements help your code make choices.

They save time and reduce mistakes compared to manual checking.

They make programs smarter and able to handle different situations.