Swift Tutorial

Swift Data Types

Swift Control Flow

Swift Functions

Swift Collections

Swift OOPs

Swift Additional Topics

Swift - Loops

In Swift, loops are a fundamental control flow mechanism that allows you to execute a block of code multiple times. Here's an overview of the types of loops in Swift:

1. For-In Loop

The for-in loop iterates over a sequence, such as items in an array, a range of numbers, or characters in a string.

  • Iterating over a range:

    for index in 1...5 {
        print("\(index) times 5 is \(index * 5)")
    }
    
  • Iterating over an array:

    let names = ["Anna", "Alex", "Brian", "Jack"]
    for name in names {
        print("Hello, \(name)!")
    }
    
  • Iterating over a dictionary:

    let numberSymbols: [Int: String] = [1: "One", 2: "Two", 3: "Three"]
    for (number, symbol) in numberSymbols {
        print("The symbol for \(number) is \(symbol)")
    }
    

2. While Loop

The while loop evaluates a condition and runs a block of code as long as the condition is true.

var count = 0
while count < 5 {
    print("Count is \(count)")
    count += 1
}

3. Repeat-While Loop

The repeat-while loop is similar to the while loop but checks the condition after the code has run, ensuring the loop runs at least once.

var number = 0
repeat {
    print("Number is \(number)")
    number += 1
} while number < 5

4. Control Transfer Statements

While working with loops, you often need control transfer statements to modify the execution flow:

  • continue: The continue statement tells the loop to stop the current iteration and start the next one.

    for num in 1...10 {
        if num % 2 == 0 {
            continue
        }
        print(num)  // This will print only odd numbers.
    }
    
  • break: The break statement ends the execution of an entire loop.

    var sum = 0
    for number in 1...10 {
        sum += number
        if sum > 15 {
            break
        }
    }
    
  • Labeled Statements: You can label a loop or condition statement, and then use break or continue with that label, allowing for more precise control transfer.

    outerLoop: for i in 1...5 {
        for j in 1...5 {
            if i * j == 12 {
                break outerLoop
            }
        }
    }
    

Remember, when using loops, always ensure there's a clear exit condition to avoid infinite loops, which could cause your program to become unresponsive.

  1. Looping through arrays with for-in in Swift:

    Description: Swift's for-in loop is a concise way to iterate over each element in an array.

    let numbers = [1, 2, 3, 4, 5]
    for number in numbers {
        print(number)
    }
    
  2. Nested loops in Swift programming:

    Description: You can nest one or more loops inside another to create more complex iteration patterns.

    for i in 1...3 {
        for j in 1...3 {
            print("(\(i), \(j))")
        }
    }
    
  3. Swift repeat-while loop usage:

    Description: The repeat-while loop in Swift repeats a block of code until a condition becomes false.

    var count = 0
    repeat {
        print("Count: \(count)")
        count += 1
    } while count < 5
    
  4. Loop control flow statements in Swift:

    Description: Swift provides break and continue statements to control the flow of a loop.

    for i in 1...5 {
        if i == 3 {
            break // exits the loop when i is 3
        }
        print(i)
    }
    
  5. Handling ranges with loops in Swift:

    Description: Ranges can be used to define a sequence of values to iterate over.

    for number in stride(from: 0, to: 10, by: 2) {
        print(number)
    }
    
  6. Swift break and continue statements in loops:

    Description: break is used to exit a loop prematurely, and continue is used to skip the rest of the code inside the loop for the current iteration.

    for i in 1...5 {
        if i % 2 == 0 {
            continue // skips even numbers
        }
        print(i)
    }