DEV Community

Gamya
Gamya

Posted on

Swift Conditions — Teaching Your Code How to Make Decisions

So far our Swift code has run straight from top to bottom — every line executes, every time. But real apps don't work like that. A game needs to check if you've won. A login screen needs to check if the password is correct. A chat app needs to check if a message is empty before sending.

This is where conditions come in — teaching your code how to make decisions. 🧠


🔀 The if Statement

The most fundamental way to check a condition in Swift is the if statement:

if someCondition {
    print("Do something")
}
Enter fullscreen mode Exit fullscreen mode

Breaking it down:

  • if tells Swift we want to check something
  • someCondition is what we're checking — it must be true or false
  • The code inside the { } (curly braces) only runs if the condition is true

You can put as many lines as you want inside those braces:

if someCondition {
    print("First thing")
    print("Second thing")
    print("Third thing")
}
Enter fullscreen mode Exit fullscreen mode

⚖️ Comparison Operators

To write conditions, you need comparison operators — symbols that compare two values and return true or false.

Here's the full set:

Operator Meaning Example
> Greater than score > 80
< Less than score < 50
>= Greater than or equal age >= 18
<= Less than or equal health <= 0
== Equal to name == "Naruto"
!= Not equal to status != "dead"

🎯 Checking Numbers

Let's say you're tracking a shinobi's power level and want to react when it crosses a threshold:

let chakraLevel = 92
let missionRank = 85
let age = 18

if chakraLevel >= 90 {
    print("Chakra levels are at peak condition!")
}

if missionRank < 85 {
    print("Sorry, you didn't pass the mission requirements.")
}

if age >= 18 {
    print("Eligible for S-rank missions.")
}
Enter fullscreen mode Exit fullscreen mode

Output:

Chakra levels are at peak condition!
Eligible for S-rank missions.
Enter fullscreen mode Exit fullscreen mode

The second if doesn't run — missionRank is exactly 85, not less than 85. That one small difference matters. ⚠️


🔤 Comparing Strings

Here's something cool — comparison operators work on strings too, not just numbers. Swift compares them alphabetically, right out of the box:

let hero = "Naruto"
let rival = "Sasuke"

if hero < rival {
    print("It's \(hero) vs \(rival)")
}

if hero > rival {
    print("It's \(rival) vs \(hero)")
}
Enter fullscreen mode Exit fullscreen mode

Output:

It's Naruto vs Sasuke
Enter fullscreen mode Exit fullscreen mode

"Naruto" comes before "Sasuke" alphabetically, so the first condition is true and the second is false. The same logic you'd use for numbers works perfectly for strings. 🌸


🆚 Checking Equality

Two operators handle equality checks — and it's important not to mix them up:

let village = "Hidden Leaf"

if village == "Hidden Leaf" {
    print("Welcome home, shinobi.")
}

if village != "Hidden Sand" {
    print("You're not from the Sand Village.")
}
Enter fullscreen mode Exit fullscreen mode

Output:

Welcome home, shinobi.
You're not from the Sand Village.
Enter fullscreen mode Exit fullscreen mode

⚠️ Common mistake: = assigns a value. == compares values. They look similar but do completely different things!


📋 Checking Arrays

You can use conditions with everything we've learned so far — including arrays. Here's a practical pattern you'll use constantly in real apps:

var squadMembers = ["Naruto", "Sasuke", "Sakura"]

squadMembers.append("Sai")

if squadMembers.count > 3 {
    squadMembers.remove(at: 0)
    print("Squad is full — oldest member removed.")
}

print(squadMembers)
Enter fullscreen mode Exit fullscreen mode

Output:

Squad is full  oldest member removed.
["Sasuke", "Sakura", "Sai"]
Enter fullscreen mode Exit fullscreen mode

🕳️ Checking for Empty Strings

This one comes up all the time in real apps — checking if a user left a text field blank. Here are three ways to do it, from worst to best:

Option 1 — Compare to an empty string (works, but slow for long strings):

var username = ""

if username == "" {
    username = "Anonymous"
}
Enter fullscreen mode Exit fullscreen mode

Option 2 — Check the count (better, but still slow in Swift):

if username.count == 0 {
    username = "Anonymous"
}
Enter fullscreen mode Exit fullscreen mode

💡 In Swift, .count on a string actually goes through and counts every character one by one — even emoji and complex Unicode characters. For a huge string, that's a lot of unnecessary work just to check if it's empty.

Option 3 — Use .isEmpty ✅ (the Swift way):

if username.isEmpty {
    username = "Anonymous"
}

print("Welcome, \(username)!")
Enter fullscreen mode Exit fullscreen mode

Output:

Welcome, Anonymous!
Enter fullscreen mode Exit fullscreen mode

.isEmpty is specifically designed to check emptiness — it's fast, clean, and works the same way on strings, arrays, dictionaries, and sets. Always prefer this. 🏆


🌐 Swift Can Compare Almost Anything

What makes Swift's comparison system really powerful is how broadly it applies. You've seen it work on Int, String, and arrays — but it goes even further.

Swift has a special type for dates called Date, and you can compare dates the exact same way:

// someDate < someOtherDate   ← totally valid in Swift
Enter fullscreen mode Exit fullscreen mode

And even enums can be made comparable. Imagine ranking jutsu difficulty:

enum JutsuRank: Comparable {
    case genin
    case chunin
    case jonin
    case kage
}

let beginnerMove = JutsuRank.genin
let masterMove = JutsuRank.kage

if beginnerMove < masterMove {
    print("Kage-level jutsu is harder than Genin-level.")
}
Enter fullscreen mode Exit fullscreen mode

Output:

Kage-level jutsu is harder than Genin-level.
Enter fullscreen mode Exit fullscreen mode

Swift compares enum cases based on the order they're listed — genin comes first, so it's "less than" kage. Clean, readable, and powerful. 💪


🧩 Putting It All Together

Here's a mini battle checker combining everything:

var playerHealth = 75
var bossHealth = 0
var playerName = ""

// Check if player name is set
if playerName.isEmpty {
    playerName = "Shinobi"
}

// Check player health
if playerHealth > 50 {
    print("\(playerName) is in good shape!")
}

if playerHealth <= 25 {
    print("\(playerName) is in critical condition!")
}

// Check if boss is defeated
if bossHealth == 0 {
    print("The boss has been defeated! Victory!")
}
Enter fullscreen mode Exit fullscreen mode

Output:

Shinobi is in good shape!
The boss has been defeated! Victory!
Enter fullscreen mode Exit fullscreen mode

🌟 Wrap Up

if statements are the backbone of any app's logic. Here's what to remember:

  • if condition { } — runs the code block only when the condition is true
  • Comparison operators — >, <, >=, <=, ==, != — work on numbers, strings, dates, and even enums
  • Use == to check equality, never = (that's assignment!)
  • Use .isEmpty instead of .count == 0 for checking empty strings, arrays, and collections — it's faster and cleaner
  • The condition inside if must always boil down to true or false — Swift won't accept anything else

Conditions are everywhere in real apps — form validation, game logic, permissions, UI changes. Nail this and you've unlocked one of the most fundamental skills in programming.

Top comments (0)