Bird
Raised Fist0
Swiftprogramming~15 mins

If and if-else statements in Swift - Deep Dive

Choose your learning style10 modes available
Overview - If and if-else statements
What is it?
If and if-else statements are ways to make decisions in a program. They let the program choose different actions based on conditions. An if statement runs code only when a condition is true. An if-else statement runs one set of code if the condition is true, and another set if it is false.
Why it matters
Without if and if-else statements, programs would do the same thing every time, no matter what. These statements let programs react to different situations, like checking if a password is correct or if a number is positive. This makes programs flexible and useful in real life.
Where it fits
Before learning if statements, you should understand basic Swift syntax and variables. After mastering if and if-else, you can learn about switch statements and loops to handle more complex decision-making and repetition.
Mental Model
Core Idea
If and if-else statements let your program choose between actions based on true or false questions.
Think of it like...
It's like deciding what to wear: if it's raining, you wear a raincoat; else, you wear a t-shirt.
┌───────────────┐
│ Condition?    │
├───────────────┤
│ True  │ False │
│       │       │
▼       ▼       ▼
[Do A]  [Do B]  [End]
Build-Up - 6 Steps
1
FoundationBasic if statement syntax
🤔
Concept: Introduces the simplest form of decision-making using if statements.
In Swift, an if statement looks like this: if condition { // code runs only if condition is true } Example: let number = 10 if number > 5 { print("Number is greater than 5") }
Result
The program prints "Number is greater than 5" only if the number is more than 5.
Understanding the basic if statement is the first step to making programs that react to different situations.
2
FoundationUsing conditions with comparison operators
🤔
Concept: Shows how to write conditions using operators like >, <, ==, and !=.
Conditions check if something is true or false. Common operators: - > means greater than - < means less than - == means equal to - != means not equal to Example: let age = 18 if age == 18 { print("You are exactly 18 years old") }
Result
The program prints "You are exactly 18 years old" if age equals 18.
Knowing how to write conditions lets you ask questions your program can answer with true or false.
3
IntermediateIf-else statement for two choices
🤔Before reading on: do you think if-else runs both code blocks or only one? Commit to your answer.
Concept: Introduces if-else to choose between two paths depending on a condition.
If-else lets your program do one thing if a condition is true, and another if it is false. Example: let temperature = 30 if temperature > 25 { print("It's hot outside") } else { print("It's not hot outside") }
Result
The program prints "It's hot outside" if temperature is above 25, otherwise it prints "It's not hot outside".
Understanding if-else helps you handle situations where you want different actions for true and false conditions.
4
IntermediateCombining multiple conditions with else if
🤔Before reading on: do you think else if lets you check multiple conditions one after another? Commit to your answer.
Concept: Shows how to check several conditions in order using else if blocks.
You can test many conditions by adding else if between if and else. Example: let score = 75 if score >= 90 { print("Grade A") } else if score >= 80 { print("Grade B") } else if score >= 70 { print("Grade C") } else { print("Grade F") }
Result
The program prints "Grade C" because score is 75, which matches the third condition.
Using else if lets your program pick the first true condition among many, making decisions more precise.
5
AdvancedNested if statements for complex decisions
🤔Before reading on: do you think nested ifs run inner conditions only if outer conditions are true? Commit to your answer.
Concept: Explains how to put if statements inside others to check conditions step-by-step.
You can put an if or if-else inside another if or else block. Example: let age = 20 let hasID = true if age >= 18 { if hasID { print("Allowed to enter") } else { print("Show your ID") } } else { print("Not allowed") }
Result
The program prints "Allowed to enter" only if age is 18 or more and hasID is true.
Nested ifs let you check multiple related conditions in a clear, stepwise way.
6
ExpertUsing if statements with optional binding
🤔Before reading on: do you think if can safely check if a value exists inside an optional? Commit to your answer.
Concept: Shows how if can unwrap optionals safely using optional binding with let.
In Swift, optionals may hold a value or nil. You can use if to check and unwrap: let name: String? = "Alice" if let unwrappedName = name { print("Hello, \(unwrappedName)") } else { print("No name provided") }
Result
The program prints "Hello, Alice" if name has a value, otherwise "No name provided".
Knowing optional binding with if prevents crashes and makes your code safer when dealing with optional values.
Under the Hood
When the program reaches an if statement, it evaluates the condition inside the parentheses. This condition must result in true or false. If true, the code inside the if block runs; if false, the program skips it or runs the else block if present. Swift uses short-circuit evaluation, so it stops checking conditions as soon as one is true in else if chains.
Why designed this way?
If statements were designed to mimic human decision-making in code, making programs flexible. Swift's design emphasizes safety and clarity, so conditions must be Boolean expressions. Optional binding with if was added to safely handle values that might be missing, avoiding crashes common in earlier languages.
┌───────────────┐
│ Evaluate cond │
├───────────────┤
│ True  │ False │
│       │       │
▼       ▼       ▼
[Run if block] [Run else block or skip]
       │           │
       └─────┬─────┘
             ▼
          Continue
Myth Busters - 4 Common Misconceptions
Quick: Does an if-else statement run both blocks or only one? Commit to your answer.
Common Belief:If-else runs both the if and else blocks every time.
Tap to reveal reality
Reality:Only one block runs: if the condition is true, the if block runs; otherwise, the else block runs.
Why it matters:Running both blocks would cause wrong behavior and bugs, like printing conflicting messages.
Quick: Can you use any type (like numbers or strings) directly as a condition in Swift? Commit to yes or no.
Common Belief:You can use numbers or strings directly as conditions without comparison.
Tap to reveal reality
Reality:Swift requires conditions to be Boolean (true or false). You must compare values explicitly.
Why it matters:Trying to use non-Boolean conditions causes compile errors, stopping your program from running.
Quick: Does else if check all conditions even after one is true? Commit to yes or no.
Common Belief:Else if checks every condition even if a previous one was true.
Tap to reveal reality
Reality:Else if stops checking as soon as it finds a true condition and runs that block only.
Why it matters:Knowing this prevents writing inefficient or incorrect code that expects multiple blocks to run.
Quick: Does optional binding with if change the original optional variable? Commit to yes or no.
Common Belief:Optional binding modifies the original optional variable directly.
Tap to reveal reality
Reality:Optional binding creates a new constant or variable with the unwrapped value; the original optional stays unchanged.
Why it matters:Misunderstanding this can lead to confusion about variable states and bugs in code logic.
Expert Zone
1
Swift's if statements require explicit Boolean conditions, unlike some languages that allow truthy/falsy values, which improves code safety.
2
Optional binding with if not only unwraps optionals but also introduces a new scope-limited constant, helping avoid accidental reuse of nil values.
3
Using guard statements can sometimes be a clearer alternative to nested ifs for early exits, improving code readability.
When NOT to use
If you have many conditions based on the same variable, switch statements are often clearer and more efficient. For repeated checks or complex logic, consider using guard statements or polymorphism instead of deeply nested ifs.
Production Patterns
In real-world Swift apps, if and if-else statements are used for input validation, feature toggles, and error handling. Optional binding with if is a common pattern to safely work with user input or network data that might be missing.
Connections
Switch statements
Switch statements build on if-else by handling multiple conditions more cleanly.
Understanding if-else helps grasp switch, which is a more organized way to choose between many options.
Boolean logic
If statements rely on Boolean logic to decide true or false outcomes.
Knowing Boolean logic deepens your understanding of how conditions combine and evaluate.
Decision making in psychology
Both involve evaluating conditions to choose actions.
Recognizing that programming decisions mimic human choices helps appreciate why if statements are fundamental.
Common Pitfalls
#1Using assignment (=) instead of comparison (==) in conditions.
Wrong approach:if age = 18 { print("Age is 18") }
Correct approach:if age == 18 { print("Age is 18") }
Root cause:Confusing the single equals sign for assignment with the double equals for comparison.
#2Forgetting to include braces {} around the if or else code blocks.
Wrong approach:if isSunny print("Go outside") else print("Stay inside")
Correct approach:if isSunny { print("Go outside") } else { print("Stay inside") }
Root cause:Not knowing that Swift requires braces for multi-line or even single-line blocks to avoid ambiguity.
#3Trying to use a non-Boolean value directly as a condition.
Wrong approach:if number { print("Number exists") }
Correct approach:if number != 0 { print("Number exists") }
Root cause:Misunderstanding that conditions must be true or false, not just any value.
Key Takeaways
If and if-else statements let your program make choices by checking true or false conditions.
Conditions must be Boolean expressions that clearly say true or false in Swift.
Else if lets you check multiple conditions in order, running only the first true block.
Optional binding with if safely unwraps values that might be missing, preventing crashes.
Using if statements well makes your programs flexible, safe, and able to handle many situations.

Practice

(1/5)
1. What does an if statement do in Swift?
easy
A. It runs code only if a condition is true.
B. It repeats code multiple times.
C. It stores data in a variable.
D. It defines a new function.

Solution

  1. Step 1: Understand the purpose of if statement

    An if statement checks a condition and runs code only when that condition is true.
  2. Step 2: Compare with other options

    Repeating code is done by loops, storing data is done by variables, and defining functions uses func.
  3. Final Answer:

    It runs code only if a condition is true. -> Option A
  4. Quick Check:

    If statement = runs code if true [OK]
Hint: If checks true condition to run code, else skips it [OK]
Common Mistakes:
  • Confusing if with loops
  • Thinking if stores data
  • Mixing if with function definitions
2. Which of the following is the correct syntax for an if-else statement in Swift?
easy
A. if condition { } else { }
B. if (condition) then { } else { }
C. if condition then { } else { }
D. if condition: { } else: { }

Solution

  1. Step 1: Recall Swift if-else syntax

    Swift uses if condition { } and else { } blocks without extra keywords like 'then' or colons.
  2. Step 2: Check each option

    if condition { } else { } matches Swift syntax exactly. Options A, B, and C use invalid keywords or punctuation.
  3. Final Answer:

    if condition { } else { } -> Option A
  4. Quick Check:

    Swift if-else = if condition { } else { } [OK]
Hint: Swift uses braces {} without 'then' or colons in if-else [OK]
Common Mistakes:
  • Adding 'then' keyword
  • Using colons after if or else
  • Putting condition in parentheses unnecessarily
3. What will be printed by this Swift code?
let number = 10
if number > 5 {
    print("Big")
} else {
    print("Small")
}
medium
A. Small
B. No output
C. 10
D. Big

Solution

  1. Step 1: Evaluate the condition

    The variable number is 10. The condition number > 5 is true because 10 is greater than 5.
  2. Step 2: Determine which block runs

    Since the condition is true, the code inside the if block runs, printing "Big".
  3. Final Answer:

    Big -> Option D
  4. Quick Check:

    10 > 5 is true, so prints "Big" [OK]
Hint: Check condition true? Run if block, else run else block [OK]
Common Mistakes:
  • Confusing which block runs
  • Printing variable instead of string
  • Ignoring condition result
4. Find the error in this Swift code:
let age = 18
if age >= 18
    print("Adult")
else
    print("Minor")
medium
A. Variable age should be a string
B. Wrong comparison operator
C. Missing braces { } around if and else blocks
D. No error, code is correct

Solution

  1. Step 1: Check Swift if-else syntax

    Swift requires braces { } around the code blocks after if and else.
  2. Step 2: Identify missing braces

    The code lacks braces after if age >= 18 and else, causing a syntax error.
  3. Final Answer:

    Missing braces { } around if and else blocks -> Option C
  4. Quick Check:

    Swift needs braces for if-else blocks [OK]
Hint: Always use { } after if and else in Swift [OK]
Common Mistakes:
  • Omitting braces in if-else
  • Using wrong operators
  • Wrong variable types
5. You want to write Swift code that prints "Positive", "Negative", or "Zero" depending on the value of an integer variable num. Which code correctly uses if-else statements to do this?
hard
A. if num >= 0 { print("Positive") } else if num <= 0 { print("Negative") } else { print("Zero") }
B. if num > 0 { print("Positive") } else if num < 0 { print("Negative") } else { print("Zero") }
C. if num > 0 { print("Positive") } else { print("Negative") } print("Zero")
D. if num == 0 { print("Zero") } else if num > 0 { print("Negative") } else if num < 0 { print("Positive") }

Solution

  1. Step 1: Understand the conditions needed

    We need to check if num is greater than 0, less than 0, or exactly 0.
  2. Step 2: Analyze each option

    if num > 0 { print("Positive") } else if num < 0 { print("Negative") } else { print("Zero") } correctly checks >0, then <0, else zero. if num >= 0 { print("Positive") } else if num <= 0 { print("Negative") } else { print("Zero") } wrongly overlaps conditions. if num > 0 { print("Positive") } else { print("Negative") } print("Zero") prints "Zero" always. if num == 0 { print("Zero") } else if num > 0 { print("Negative") } else if num < 0 { print("Positive") } incorrectly prints "Negative" for positive numbers and "Positive" for negative numbers.
  3. Final Answer:

    if num > 0 { print("Positive") } else if num < 0 { print("Negative") } else { print("Zero") } -> Option B
  4. Quick Check:

    Check >0, else if <0, else zero [OK]
Hint: Check positive first, then negative, else zero last [OK]
Common Mistakes:
  • Overlapping conditions causing wrong output
  • Printing zero outside else block
  • Wrong order of conditions
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard