DEV Community

Gamya
Gamya

Posted on Edited 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")
}
🔴 Hot News: gamya m/swift conditions teaching your code how to make decisions i - สรุปดราม่าล่าสุด 🔴 Hot News: gamya m/swift conditions teaching your code how to make decisions i - สรุปดราม่าล่าสุด

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")
}
🔴 Hot News: gamya m/swift conditions teaching your code how to make decisions i - สรุปดราม่าล่าสุด 🔴 Hot News: gamya m/swift conditions teaching your code how to make decisions i - สรุปดราม่าล่าสุด

⚖️ 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.")
}
🔴 Hot News: gamya m/swift conditions teaching your code how to make decisions i - สรุปดราม่าล่าสุด 🔴 Hot News: gamya m/swift conditions teaching your code how to make decisions i - สรุปดราม่าล่าสุด

Output:

Chakra levels are at peak condition!
Eligible for S-rank missions.
🔴 Hot News: gamya m/swift conditions teaching your code how to make decisions i - สรุปดราม่าล่าสุด 🔴 Hot News: gamya m/swift conditions teaching your code how to make decisions i - สรุปดราม่าล่าสุด

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)")
}
🔴 Hot News: gamya m/swift conditions teaching your code how to make decisions i - สรุปดราม่าล่าสุด 🔴 Hot News: gamya m/swift conditions teaching your code how to make decisions i - สรุปดราม่าล่าสุด

Output:

It's Naruto vs Sasuke
🔴 Hot News: gamya m/swift conditions teaching your code how to make decisions i - สรุปดราม่าล่าสุด 🔴 Hot News: gamya m/swift conditions teaching your code how to make decisions i - สรุปดราม่าล่าสุด

"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.")
}
🔴 Hot News: gamya m/swift conditions teaching your code how to make decisions i - สรุปดราม่าล่าสุด 🔴 Hot News: gamya m/swift conditions teaching your code how to make decisions i - สรุปดราม่าล่าสุด

Output:

Welcome home, shinobi.
You're not from the Sand Village.
🔴 Hot News: gamya m/swift conditions teaching your code how to make decisions i - สรุปดราม่าล่าสุด 🔴 Hot News: gamya m/swift conditions teaching your code how to make decisions i - สรุปดราม่าล่าสุด

⚠️ 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)
🔴 Hot News: gamya m/swift conditions teaching your code how to make decisions i - สรุปดราม่าล่าสุด 🔴 Hot News: gamya m/swift conditions teaching your code how to make decisions i - สรุปดราม่าล่าสุด

Output:

Squad is full — oldest member removed.
["Sasuke", "Sakura", "Sai"]
🔴 Hot News: gamya m/swift conditions teaching your code how to make decisions i - สรุปดราม่าล่าสุด 🔴 Hot News: gamya m/swift conditions teaching your code how to make decisions i - สรุปดราม่าล่าสุด

🕳️ 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"
}
🔴 Hot News: gamya m/swift conditions teaching your code how to make decisions i - สรุปดราม่าล่าสุด 🔴 Hot News: gamya m/swift conditions teaching your code how to make decisions i - สรุปดราม่าล่าสุด

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

if username.count == 0 {
    username = "Anonymous"
}
🔴 Hot News: gamya m/swift conditions teaching your code how to make decisions i - สรุปดราม่าล่าสุด 🔴 Hot News: gamya m/swift conditions teaching your code how to make decisions i - สรุปดราม่าล่าสุด

💡 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)!")
🔴 Hot News: gamya m/swift conditions teaching your code how to make decisions i - สรุปดราม่าล่าสุด 🔴 Hot News: gamya m/swift conditions teaching your code how to make decisions i - สรุปดราม่าล่าสุด

Output:

Welcome, Anonymous!
🔴 Hot News: gamya m/swift conditions teaching your code how to make decisions i - สรุปดราม่าล่าสุด 🔴 Hot News: gamya m/swift conditions teaching your code how to make decisions i - สรุปดราม่าล่าสุด

.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
🔴 Hot News: gamya m/swift conditions teaching your code how to make decisions i - สรุปดราม่าล่าสุด 🔴 Hot News: gamya m/swift conditions teaching your code how to make decisions i - สรุปดราม่าล่าสุด

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.")
}
🔴 Hot News: gamya m/swift conditions teaching your code how to make decisions i - สรุปดราม่าล่าสุด 🔴 Hot News: gamya m/swift conditions teaching your code how to make decisions i - สรุปดราม่าล่าสุด

Output:

Kage-level jutsu is harder than Genin-level.
🔴 Hot News: gamya m/swift conditions teaching your code how to make decisions i - สรุปดราม่าล่าสุด 🔴 Hot News: gamya m/swift conditions teaching your code how to make decisions i - สรุปดราม่าล่าสุด

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!")
}
🔴 Hot News: gamya m/swift conditions teaching your code how to make decisions i - สรุปดราม่าล่าสุด 🔴 Hot News: gamya m/swift conditions teaching your code how to make decisions i - สรุปดราม่าล่าสุด

Output:

Shinobi is in good shape!
The boss has been defeated! Victory!
🔴 Hot News: gamya m/swift conditions teaching your code how to make decisions i - สรุปดราม่าล่าสุด 🔴 Hot News: gamya m/swift conditions teaching your code how to make decisions i - สรุปดราม่าล่าสุด

🌟 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 (2)

🔴 Hot News: gamya m/swift conditions teaching your code how to make decisions i - สรุปดราม่าล่าสุด
 
junhao profile image
Ahmed bahar •

MY DEAR GIRL
You explain things so clearly and beautifully. Thank you for making Swift easy to learn! ❤️🌸

🔴 Hot News: gamya m/swift conditions teaching your code how to make decisions i - สรุปดราม่าล่าสุด
 
gamya_m profile image
Gamya •

Thank you so much; that really means a lot! 🌸 Comments like yours make it all worth it. More articles are on the way — hope they continue to be helpful! 😊✨