Skip to main content

Swift Conditional Statements

In programming, making decisions is a fundamental concept. Swift offers several ways to branch your code based on conditions, allowing your program to execute different code paths depending on whether certain conditions are true or false.

Introduction

Conditional statements are control flow structures that help your program make decisions. They evaluate boolean expressions (conditions that are either true or false) and execute specific code blocks based on the result of that evaluation.

Swift provides several types of conditional statements:

  • if, else if, and else statements
  • switch statements
  • guard statements

Let's explore each of these to understand how they work and when to use them.

The if Statement

The simplest form of conditional statement is the if statement. It executes a block of code only if a specified condition is true.

Basic Syntax

swift
if condition {
// code to execute if condition is true
}

Example

swift
let temperature = 25

if temperature > 20 {
print("It's a warm day!")
}

Output:

It's a warm day!

In this example, since 25 is greater than 20, the message is printed.

If-Else Statement

The if-else statement allows you to execute one block of code if a condition is true, and another block if it's false.

Syntax

swift
if condition {
// code to execute if condition is true
} else {
// code to execute if condition is false
}

Example

swift
let hour = 20

if hour < 12 {
print("Good morning!")
} else {
print("Good day!")
}

Output:

Good day!

Since 20 is not less than 12, the else block executes.

If-Else If-Else Statement

For multiple conditions, Swift allows you to chain them using else if.

Syntax

swift
if firstCondition {
// code to execute if firstCondition is true
} else if secondCondition {
// code to execute if firstCondition is false and secondCondition is true
} else {
// code to execute if all conditions are false
}

Example

swift
let score = 85

if score >= 90 {
print("A grade")
} else if score >= 80 {
print("B grade")
} else if score >= 70 {
print("C grade")
} else if score >= 60 {
print("D grade")
} else {
print("F grade")
}

Output:

B grade

The score is 85, which falls in the B grade range (80-89).

Nested If Statements

You can also nest if statements inside other if statements for more complex logic.

Example

swift
let age = 25
let hasDriverLicense = true

if age >= 18 {
if hasDriverLicense {
print("You can drive a car")
} else {
print("You are old enough but need a license")
}
} else {
print("You are too young to drive")
}

Output:

You can drive a car

Ternary Conditional Operator

Swift provides a shorthand for simple if-else statements using the ternary operator ?:.

Syntax

swift
condition ? valueIfTrue : valueIfFalse

Example

swift
let age = 17
let message = age >= 18 ? "You are an adult" : "You are a minor"
print(message)

Output:

You are a minor

This is equivalent to:

swift
let age = 17
let message: String

if age >= 18 {
message = "You are an adult"
} else {
message = "You are a minor"
}

print(message)

Switch Statement

The switch statement compares a value against multiple possible matching patterns and executes the code block associated with the first matching pattern.

Basic Syntax

swift
switch value {
case pattern1:
// code to execute if value matches pattern1
case pattern2, pattern3:
// code to execute if value matches pattern2 or pattern3
default:
// code to execute if no patterns match
}

Example: Simple Switch

swift
let dayOfWeek = 3

switch dayOfWeek {
case 1:
print("Monday")
case 2:
print("Tuesday")
case 3:
print("Wednesday")
case 4:
print("Thursday")
case 5:
print("Friday")
case 6:
print("Saturday")
case 7:
print("Sunday")
default:
print("Invalid day")
}

Output:

Wednesday

Range Matching

Swift's switch statements can match ranges.

swift
let temperature = 28

switch temperature {
case ...0:
print("Freezing")
case 1...10:
print("Very cold")
case 11...20:
print("Cold")
case 21...30:
print("Warm")
case 31...:
print("Hot")
default:
print("Temperature undefined")
}

Output:

Warm

Value Binding

switch statements in Swift can also bind the matched value to a temporary constant or variable.

swift
let point = (2, 0)

switch point {
case (0, 0):
print("Origin")
case (_, 0):
print("On the x-axis at x = \(point.0)")
case (0, _):
print("On the y-axis at y = \(point.1)")
case let (x, y):
print("Somewhere else at (\(x), \(y))")
}

Output:

On the x-axis at x = 2

Where Clauses

switch statements can use where clauses to check for additional conditions.

swift
let point = (1, -1)

switch point {
case let (x, y) where x == y:
print("On the line x = y")
case let (x, y) where x == -y:
print("On the line x = -y")
case let (x, y):
print("Point: (\(x), \(y))")
}

Output:

On the line x = -y

The guard Statement

The guard statement is used to transfer program control out of a scope if one or more conditions aren't met. It's particularly useful for early returns and avoiding nested if statements.

Syntax

swift
guard condition else {
// code to execute if condition is false
// must exit scope (return, break, continue, or throw)
}
// code to execute if condition is true

Example

swift
func processAge(age: Int?) {
guard let age = age else {
print("Age is not provided")
return
}

guard age >= 18 else {
print("Access denied: You must be 18 or older")
return
}

print("Welcome! You're \(age) years old")
}

processAge(age: nil)
processAge(age: 15)
processAge(age: 21)

Output:

Age is not provided
Access denied: You must be 18 or older
Welcome! You're 21 years old

The guard statement is especially useful for:

  1. Early return from functions
  2. Unwrapping optionals
  3. Ensuring preconditions are met
  4. Making code more readable by reducing nesting

Real-World Applications

User Authentication

swift
func login(username: String?, password: String?) {
guard let username = username, !username.isEmpty else {
print("Error: Username cannot be empty")
return
}

guard let password = password, password.count >= 8 else {
print("Error: Password must be at least 8 characters")
return
}

if username == "admin" && password == "password123" {
print("Login successful")
} else {
print("Invalid credentials")
}
}

login(username: "", password: "pass123")
login(username: "admin", password: "pass")
login(username: "admin", password: "password123")

Output:

Error: Username cannot be empty
Error: Password must be at least 8 characters
Login successful

Temperature Converter App

swift
func convertTemperature(value: Double, from inputUnit: String, to outputUnit: String) -> Double? {
var celsiusTemp: Double

// First convert to Celsius as an intermediate step
switch inputUnit.lowercased() {
case "celsius", "c":
celsiusTemp = value
case "fahrenheit", "f":
celsiusTemp = (value - 32) * 5/9
case "kelvin", "k":
celsiusTemp = value - 273.15
default:
print("Invalid input unit")
return nil
}

// Then convert from Celsius to the output unit
switch outputUnit.lowercased() {
case "celsius", "c":
return celsiusTemp
case "fahrenheit", "f":
return celsiusTemp * 9/5 + 32
case "kelvin", "k":
return celsiusTemp + 273.15
default:
print("Invalid output unit")
return nil
}
}

if let result = convertTemperature(value: 32, from: "f", to: "c") {
print("32°F is \(result)°C")
}

if let result = convertTemperature(value: 100, from: "c", to: "f") {
print("100°C is \(result)°F")
}

Output:

32°F is 0.0°C
100°C is 212.0°F

Best Practices

  1. Keep conditions simple: Complex conditions can be hard to read and debug. Consider breaking them down or using temporary variables.

  2. Use meaningful variable names: This makes your code more readable and helps others understand your logic.

  3. Consider the default case: Always include a default case in switch statements unless you're absolutely sure you've covered all possibilities.

  4. Use guard for early returns: It makes your code more readable by reducing nesting.

  5. Be consistent with your style: Whether you put the opening brace on the same line or the next, be consistent throughout your code.

Summary

Swift offers several conditional statements to control the flow of your programs:

  • if, else if, else: For basic conditional branching
  • ternary operator: For simple, concise if-else statements
  • switch: For matching values against multiple patterns
  • guard: For early returns and avoiding nested if statements

Each has its own strengths and typical use cases. Mastering these conditional statements will give you fine-grained control over how your Swift programs execute and respond to different scenarios.

Exercises

  1. Write a program that determines if a year is a leap year (divisible by 4, except for years divisible by 100 but not by 400).

  2. Create a function that takes a character and determines whether it's a vowel, consonant, number, or special character.

  3. Implement a simple calculator that takes two numbers and an operator (+, -, *, /) and returns the result of the operation.

  4. Write a function that takes a temperature in Celsius and returns a string describing the weather (e.g., "Freezing", "Cold", "Moderate", "Warm", "Hot").

  5. Create a function that validates a password according to these rules:

    • At least 8 characters
    • Contains at least one uppercase letter
    • Contains at least one lowercase letter
    • Contains at least one number
    • Contains at least one special character

Additional Resources

Happy coding!



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)