Skip to main content
Swift for iOS Development
CHAPTER 05 Beginner

Operators, Conditions, and Loops

Updated: May 16, 2026
5 min read

# CHAPTER 5

Operators, Conditions, and Loops

1. Introduction

A program that just stores data is useless. An app must react and make decisions. If a user types the correct password, let them in; otherwise, show an error. If a user buys 5 items, calculate the total price. To implement this logic, we use Control Flow. In this chapter, we will master Operators, Conditions, and Loops. We will learn how to perform math, compare values, execute branching logic using if and switch statements, and automate repetitive tasks using loops.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Perform mathematical calculations using Arithmetic Operators.
  • Compare data using Comparison and Logical Operators (==, !=, &&, ||).
  • Write conditional branching logic using if, else if, and else.
  • Write clean multi-condition logic using the switch statement.
  • Execute repetitive code using for-in and while loops.

3. Arithmetic and Assignment Operators

Swift provides standard math operators:
  • Addition: +
  • Subtraction: -
  • Multiplication: *
  • Division: /
  • Remainder (Modulo): % (Returns the remainder of a division)

Compound Assignment: A shortcut for updating a variable!

swift
1234
var score = 10
score += 5   // Exact same as: score = score + 5
score -= 2   // Exact same as: score = score - 2
print(score) // Prints 13

4. Comparison and Logical Operators

To make a decision, you must compare data. Comparisons always result in a Boolean (true or false).
  • Equal to: ==
  • Not equal to: !=
  • Greater / Less than: >, <, >=, <=

Logical Operators (Combining conditions):

  • AND (&&): BOTH sides must be true.
  • OR (||): AT LEAST ONE side must be true.
  • NOT (!): Flips the boolean (True becomes False).

swift
12345
let age = 20
let hasTicket = true

// true AND true -> Results in true!
let canEnter = (age >= 18) && hasTicket 

5. Conditional Statements (if / else)

The if statement executes code *only* if the condition is true.
swift
123456789
let userAge = 16

if userAge >= 18 {
    print("Welcome to the app!")
} else if userAge >= 13 {
    print("Welcome, teen user. Parental controls enabled.")
} else {
    print("Sorry, you are too young to use this app.")
}

6. The switch Statement (Cleaner Conditions)

If you have many else if statements checking the exact same variable, use a switch! It is significantly cleaner and faster. *Swift Rule: Switch statements MUST be exhaustive. They must cover every possible scenario, which is why a default case is almost always required!*
swift
123456789101112
let weather = "Rain"

switch weather {
case "Sunny":
    print("Wear sunglasses 🕶️")
case "Rain":
    print("Bring an umbrella ☔️")
case "Snow":
    print("Wear a heavy coat ⛄️")
default:
    print("Check the forecast later.")
}

7. The for-in Loop

Loops allow you to execute a block of code multiple times. The for-in loop is perfect for iterating over a sequence of numbers (a Range).
  • 1...5 (Closed Range): 1, 2, 3, 4, 5
  • 1..<5 (Half-Open Range): 1, 2, 3, 4
swift
123456789
// This will print the phrase exactly 5 times!
for i in 1...5 {
    print("This is iteration number \(i)")
}

// If you don't need the number 'i', use an underscore '_' to save memory!
for _ in 1...3 {
    print("Hello!")
}

8. The while Loop

A while loop continues running code repeatedly *until* a condition becomes false. It is excellent for game loops or waiting for data. *Warning: If the condition never becomes false, you create an "Infinite Loop" and your app will crash!*
swift
1234567
var countdown = 3

while countdown > 0 {
    print("\(countdown)...")
    countdown -= 1 // We MUST decrease it, or it will loop forever!
}
print("BLASTOFF! 🚀")

9. Mini Project: Grade Calculator

Let's combine Variables, Operators, and Conditions into a logical script.
swift
123456789101112131415161718192021
let mathScore = 85
let scienceScore = 92
let englishScore = 78

// 1. Operators: Calculate the average
let totalScore = mathScore + scienceScore + englishScore
let average = totalScore / 3

print("Your average score is \(average)")

// 2. Conditions: Determine the letter grade
switch average {
case 90...100:
    print("Grade: A")
case 80..<90:
    print("Grade: B")
case 70..<80:
    print("Grade: C")
default:
    print("Grade: F (Please see the teacher)")
}

10. Common Mistakes

  • Using = instead of == in if statements: A single = is an assignment operator (giving a box a value). A double == is a comparison operator (checking if two boxes are identical). if name = "Alice" will crash the compiler! It must be if name == "Alice".
  • Forgetting the default case in a switch: Swift will rigidly refuse to compile a switch statement if it thinks there is even a 0.01% chance a value might slip through unhandled.

11. Best Practices

  • Switch over If-Else: If you are checking the same variable against 3 or more specific values, always prefer a switch statement over an if / else if chain. It compiles faster and is much easier to read.

12. Exercises

  1. 1. Write an if statement that checks if a variable isBatteryLow is true. If it is, print "Please plug in device".
  1. 2. Write a for loop that prints the numbers 10 down to 1. (Hint: Look up reversed() ranges in Swift!).

13. MCQ Quiz with Answers

Question 1

In an if statement, which Logical Operator requires BOTH conditions to evaluate to true for the code block to execute?

Question 2

Why is the default case typically mandatory when writing a switch statement evaluating a String in Swift?

14. Interview Questions

  • Q: Explain the mechanical difference between the 1...5 closed range operator and the 1..<5 half-open range operator. In what specific coding scenario is the half-open range critical?
  • Q: Contrast a for-in loop with a while loop. Provide a specific architectural scenario where a while loop is the superior choice.
  • Q: Describe the concept of an "Infinite Loop". How is it created, and what happens to an iOS application when it occurs on the main thread?

15. Summary

In Chapter 5, we injected intelligence into our code. We utilized Operators to perform complex mathematics and compare data states. We established branching architectures using if / else statements, and organized complex multi-state logic efficiently utilizing the exhaustive switch statement. Finally, we conquered automation, executing repetitive tasks seamlessly using for-in ranges and condition-dependent while loops.

16. Next Chapter Recommendation

Our logic works, but writing the exact same 10 lines of code every time we want to calculate a grade is terrible for maintenance. We need to encapsulate code into reusable machines. Proceed to Chapter 6: Functions and Closures in Swift.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·