Control Flow in Swift: Conditional Statements and Loops

February 5, 2024

We’ll delve into the control flow mechanisms in Swift, including if-else statements, switch statements, and various types of loops. We’ll provide examples to demonstrate how to use these control flow structures in Swift.

If-Else Statements

In Swift, the if-else statement is used to execute a block of code based on a condition. Here’s a simple example:

let number = 10
if number < 0 {
    print("Negative number")
} else if number == 0 {
    print("Zero")
} else {
    print("Positive number")
}

In this example, if the number is less than 0, it prints ‘Negative number.’ If the number is 0, it prints ‘Zero.’ Otherwise, it prints ‘Positive number.’

Switch Statements

Switch statements are used to compare a value against multiple possible matching patterns. Here’s an example:

let grade = "A"
switch grade {
    case "A":
        print("Excellent")
    case "B":
        print("Good")
    case "C":
        print("Fair")
    default:
        print("Needs improvement")
}

In this example, the switch statement checks the value of ‘grade’ and prints a corresponding message based on the matching pattern.

Loops

Swift provides several types of loops, including for-in loops, while loops, and repeat-while loops.

For-In Loops

A for-in loop is used to iterate over a sequence, such as a range of numbers or elements in an array. Here’s an example:

for index in 1...5 {
    print(index)
}

This loop prints the numbers 1 through 5.

While Loops

A while loop is used to repeatedly execute a block of code as long as a condition is true. Here’s an example:

var count = 0
while count < 5 {
    print(count)
    count += 1
}

This loop prints the numbers 0 through 4.

Repeat-While Loops

A repeat-while loop is similar to a while loop, but it always executes the block of code at least once before checking the condition. Here’s an example:

var i = 0
repeat {
    print(i)
    i += 1
} while i < 5

This loop also prints the numbers 0 through 4.