Loops in Swift: A Comprehensive Guide

 Loops in Swift: A Comprehensive Guide


Introduction to Loops


Loops allow us to execute a block of code repeatedly until a specific condition is met. Swift provides four types of loops: forfor-inwhile, and repeat-while. Each loop type serves different purposes depending on the use case.


For Loop


The for loop is used when the number of iterations is fixed. It repeats the code for a defined range of values.


Syntax:


for initialization; condition; increment {

    // Code to execute

}


Example:


for var i = 0; i < 5; i += 1 {

    print("Iteration \(i)")

}


This outputs:

Iteration 0

Iteration 1

Iteration 2

Iteration 3

Iteration 4


You can also use nested for loops for more complex scenarios.


for i in 1...3 {

    for j in 1...3 {

        print("i: \(i), j: \(j)")

    }

}


For-In Loop


The for-in loop is commonly used to iterate over collections such as arrays, dictionaries, ranges, and strings. It’s concise and easy to use.


Syntax:


for item in collection {

    // Code to execute

}


Example 1 (Array):


let fruits = ["Apple""Banana""Cherry"]

for fruit in fruits {

    print("I love \(fruit)")

}


Output:

I love Apple

I love Banana

I love Cherry


Example 2 (Range):


for number in 1...5 {

    print(number)

}


Example 3 (Dictionary):


let scores = ["Alice"90"Bob"85"Charlie"88]

for (name, score) in scores {

    print("\(name)\(score)")

}


The for-in loop also supports advanced features like filtering using the where clause.


for number in 1...10 where number % 2 == 0 {

    print("Even number: \(number)")

}


While Loop


The while loop is used when you want to repeat a block of code as long as a specific condition is true. It checks the condition beforeexecuting the block.


Syntax:


while condition {

    // Code to execute

}


Example:


var count = 5

while count > 0 {

    print("Countdown: \(count)")

    count -= 1

}


This outputs:

Countdown: 5

Countdown: 4

Countdown: 3

Countdown: 2

Countdown: 1


Use the while loop for tasks where the number of iterations depends on a condition, such as monitoring game health or polling for a network response.


Repeat-While Loop


The repeat-while loop is similar to the while loop but ensures the block of code is executed at least once, even if the condition is false.


Syntax:


repeat {

    // Code to execute

while condition


Example:


var number = 1

repeat {

    print("Number: \(number)")

    number += 1

while number <= 5


This outputs:

Number: 1

Number: 2

Number: 3

Number: 4

Number: 5


This loop is particularly useful for input validation or scenarios where the action must occur before checking the condition.


Best Practices for Loops

1. Avoid Infinite Loops: Ensure the loop condition changes and will eventually evaluate to false.


while true {

    print("This loop will never end unless manually stopped.")

}


2. Use Break and Continue Wisely:


break: Exits the loop immediately.

continue: Skips the current iteration and proceeds to the next.


for number in 1...10 {

    if number == 5 {

        break // Exit the loop

    }

    if number % 2 == 0 {

        continue // Skip even numbers

    }

    print(number)

}


3. Simplify Nested Loops: Minimize nesting as it can increase complexity. Replace with algorithms when possible.

4. Use Functional Methods: For collections, consider alternatives like .map.filter, or .reduce for better readability and performance.


Real-World Examples


Example 1: Processing API Responses


let apiResponses = [200404500200403]

for response in apiResponses {

    if response == 200 {

        print("Success!")

    else {

        print("Error: \(response)")

    }

}


Example 2: Fibonacci Numbers


var a = 0, b = 1

for _ in 0..<10 {

    print(a)

    let temp = a + b

    a = b

    b = temp

}


When to Use Each Loop

For Loop: Use when the number of iterations is fixed, such as iterating through a defined range.

For-In Loop: Ideal for traversing collections like arrays, dictionaries, or ranges.

While Loop: Use when the number of iterations is unknown and depends on a condition being true.

Repeat-While Loop: Use when the block of code must execute at least once, regardless of the condition.


Conclusion


Loops are essential tools for repetitive tasks and control flow. Mastering the use of forfor-inwhile, and repeat-while loops will enable you to write efficient and readable Swift code. Practice these loops with real-world scenarios to build your confidence and deepen your understanding.


        1. Swift loops tutorial

2. For loop in Swift

3. For-in loop Swift examples

4. While loop in Swift

5. Repeat-while loop Swift guide

6. Loops in Swift programming

7. Swift loop examples

8. Swift loop types

9. Using loops in Swift

10. Swift control flow loops

Comments

Popular posts from this blog

Complete iOS Developer Guide - Swift 5 by @hiren_syl |  You Must Have To Know 😎 

Debugging

Swift Fundamentals You Can’t Miss! A List by @hiren_syl