You are currently viewing Swift Looping: Everything You Need to Know

Swift Looping: Everything You Need to Know

Looping is a fundamental concept in Swift programming, allowing for repetitive tasks and efficient data processing. This article explores Swift’s loop constructs, including the for-in, while, and repeat-while loops. Additionally, we will cover essential loop control statements like break and continue. Each concept will be accompanied by concise and detailed code examples to demonstrate their practical use.

The for-in Loop

The for-in loop in Swift simplifies iterating over collections, such as arrays, sets, or ranges. It iterates over each element in the collection without the need for explicit indices.

Here’s an example that prints the elements of an array using a for-in loop:

// Array of numbers
let numbers: [Int] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

// Iterating over array elements
for number in numbers {

    print(number)
    
}

we have an array of integers called numbers that contains ten elements. The for-in loop iterates over each element in the numbers array and assigns it to the variable number. The loop body then executes the print statement, which prints the value of number to the console.

Here’s an example that prints the elements of a dictionary using a for-in loop:

// Dictionary of person information
let person: [String: String] = ["name": "Edward", "age": "26", "language": "Swift", "level": "Intermediate"]

// Iterating over dictionary elements
for (key, value) in person {

    print("\(key) = \(value)")
    
}

We have a dictionary called person that contains key-value pairs representing information about a person. The for-in loop iterates over each key-value pair in the person dictionary, assigning the key to the variable key and the value to the variable value. The loop body then executes the print statement, which prints the key and its corresponding value to the console.

Here’s an example that prints the elements of a set using a for-in loop:

// Set of programming languages
let setOfLanguages: Set<String> = ["C", "Dart", "JavaScript", "PHP", "Python", "R", "Swift"]

// Iterating over set of languages
for language in setOfLanguages {

    print(language)
    
}

We have a set called setOfLanguages that contains several programming languages. The for-in loop iterates over each element in the set, assigning it to the variable language. The loop body then executes the print statement, which prints the value of language to the console.

Here’s an example that prints the elements of an open range using a for-in loop:

// Open range of 1 through 9
let range1to9: Range<Int> = 1..<10

// Iterating over range elements
for i in range1to9 {
    print(i)
}

We have an open range called range1to9 that represents the numbers from 1 to 9 (excluding 10). The for-in loop iterates over each element in the range, assigning it to the variable i. The loop body then executes the print statement, which prints the value of i to the console.

Here’s an example that prints the elements of a closed range using a for-in loop:

// Closed range of 1 through 10
let range1to10: ClosedRange<Int> = 1...10

// Iterating over range elements
for i in range1to10 {

    print(i)
    
}

We have a closed range called range1to10 that represents the numbers from 1 to 10 (including both 1 and 10). The for-in loop iterates over each element in the range, assigning it to the variable i. The loop body then executes the print statement, which prints the value of i to the console.

By using the for-in loop, you can easily iterate over the elements of an array (or any other collection) without the need for explicit indices. The loop simplifies the process of accessing each element and performing operations on it.

The while Loop

The while loop in Swift repeats a block of code as long as a specified condition is true. It’s useful when the number of iterations is unknown beforehand. Consider the following example that prints the numbers from 1 to 10 using a while loop:

var i = 1

while i <= 10 {

    print(i)
    
    // Increment variable i
    i += 1
    
}

We initialize a variable i to 1. The while loop checks if i is less than or equal to 10. If true, it prints the value of i and increments it by 1 using i += 1. The loop continues until the condition becomes false.

The repeat-while Loop

The repeat-while loop in Swift is similar to the do-while loop in other languages. It repeats a block of code until a specified condition is false. Unlike the while loop, the code block is always executed at least once. Let’s see an example that uses a repeat-while loop to repeatedly asks the user to enter a value until they enter “q” (case-insensitive).

var exitKey: String

repeat {

    print("Enter 'q' to terminate program: ")
    
    exitKey = readLine()!.lowercased()
    
} while exitKey != "q"

print("Exiting Program...")

The readLine() function is used to read user input from the console, and lowercased() is used to convert the input to lowercase for case-insensitive comparison. Once the user enters “q”, the loop terminates, and the program prints “Exiting Programโ€ฆ” to indicate program termination.

The repeat-while loop is useful when you want to execute a block of code at least once and then continue looping as long as a specified condition remains true.

Loop Control Statements: break and continue

Swift provides loop control statements like break and continue to alter the flow of a loop.

The break statement is used to terminate a loop prematurely. When encountered, it immediately exits the loop and transfers control to the next statement after the loop. Here’s an example that finds the first even number in an array using a for-in loop with a break statement:

let numbers = [1, 3, 2, 5, 8, 7, 9, 10, 4, 6]

for number in numbers {

    if number % 2 == 0 {
    
        print("First even number found: \(number)")
        
        // Exit loop
        break
        
    }
    
}

print("Free. Out of loop!!!")

The for-in loop iterates over the elements in the numbers array. When it encounters an even number, the break statement is executed, terminating the loop.

The continue statement is used to skip the remaining code in a loop iteration and move to the next iteration. It allows you to selectively execute the code based on certain conditions. Consider an example that prints only odd numbers from 1 to 10 using a for-in loop with a continue statement:

for number in 1...10 {

    if number % 2 == 0 {
        // Even number, move to next iteration
        continue
    }
    
    print(number)
    
}

The for-in loop iterates over the range of numbers from 1 to 10. If a number is even, the continue statement is executed, skipping the remaining code in that iteration. As a result, only odd numbers are printed to the console.

Conclusion

Looping is an essential concept in programming, and Swift provides powerful loop constructs to handle different scenarios. This article explored the for-in, while, and repeat-while loops, along with loop control statements like break and continue. We also provided detailed code examples to illustrate their usage and demonstrate how they can be applied in practical scenarios. By mastering these looping concepts, you’ll be able to write more efficient and expressive code in Swift.

Sources

I hope you found this information informative. If you would like to receive more content, please consider subscribing to our newsletter!

Leave a Reply