Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Swift Programming - Control Flow

Introduction

Control flow in Swift refers to the order in which code is executed. Swift provides several control flow constructs to manage this order efficiently, including loops, conditional statements, and control transfer statements. Understanding these constructs is essential for writing effective Swift programs.

If Statement

The if statement is used to execute a block of code only if a specified condition is true.

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

Example:

let temperature = 30
if temperature > 25 {
    print("It's a hot day!")
}
                
Output: It's a hot day!

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 is false.

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

Example:

let temperature = 20
if temperature > 25 {
    print("It's a hot day!")
} else {
    print("It's a cool day!")
}
                
Output: It's a cool day!

Switch Statement

The switch statement evaluates a value and matches it against several cases. It is often used as an alternative to multiple if-else statements.

switch value {
case pattern1:
    // code to execute if value matches pattern1
case pattern2:
    // code to execute if value matches pattern2
default:
    // code to execute if no pattern matches
}
                

Example:

let day = "Tuesday"
switch day {
case "Monday":
    print("Start of the workweek")
case "Tuesday":
    print("Second day of the workweek")
default:
    print("Another day")
}
                
Output: Second day of the workweek

For-In Loop

The for-in loop is used to iterate over a sequence, such as items in an array, ranges of numbers, or characters in a string.

for item in sequence {
    // code to execute for each item
}
                

Example:

let fruits = ["Apple", "Banana", "Cherry"]
for fruit in fruits {
    print("I like \(fruit)")
}
                
Output: I like Apple
I like Banana
I like Cherry

While Loop

The while loop is used to repeat a block of code as long as a specified condition is true.

while condition {
    // code to execute while condition is true
}
                

Example:

var count = 5
while count > 0 {
    print("Count is \(count)")
    count -= 1
}
                
Output: Count is 5
Count is 4
Count is 3
Count is 2
Count is 1

Repeat-While Loop

The repeat-while loop is similar to the while loop, but it always executes the block of code at least once before checking the condition.

repeat {
    // code to execute
} while condition
                

Example:

var count = 5
repeat {
    print("Count is \(count)")
    count -= 1
} while count > 0
                
Output: Count is 5
Count is 4
Count is 3
Count is 2
Count is 1

Control Transfer Statements

Swift provides several control transfer statements for changing the order in which code is executed. These include continue, break, fallthrough, return, and throw.

Continue

The continue statement tells a loop to stop what it is doing and start again at the beginning of the next iteration.

for i in 1...5 {
    if i == 3 {
        continue
    }
    print(i)
}
                
Output: 1
2
4
5

Break

The break statement ends the execution of a loop or a switch statement.

for i in 1...5 {
    if i == 3 {
        break
    }
    print(i)
}
                
Output: 1
2

Fallthrough

The fallthrough statement causes the program to continue execution at the next case in a switch statement.

let number = 4
switch number {
case 4:
    print("Number is 4")
    fallthrough
case 5:
    print("Number is 5")
default:
    print("Number is something else")
}
                
Output: Number is 4
Number is 5
Number is something else

Return

The return statement ends the execution of a function and returns control to the calling function.

func greet(person: String) -> String {
    return "Hello, \(person)!"
}
print(greet(person: "John"))
                
Output: Hello, John!

Throw

The throw statement is used to throw an error in Swift. It is often used in functions that can produce errors.

enum PrinterError: Error {
    case outOfPaper
    case noToner
    case onFire
}

func sendToPrinter(job: Int) throws {
    if job == 0 {
        throw PrinterError.outOfPaper
    }
    print("Job sent")
}

do {
    try sendToPrinter(job: 0)
} catch PrinterError.outOfPaper {
    print("Out of paper")
} catch {
    print("Unknown error")
}
                
Output: Out of paper