Swift Tutorial

Swift Data Types

Swift Control Flow

Swift Functions

Swift Collections

Swift OOPs

Swift Additional Topics

Swift - For-in Loop

In Swift, the for-in loop is a powerful construct used to iterate over a sequence, such as items in an array, characters in a string, or even key-value pairs in a dictionary. It provides a concise way to run a set of statements for each item in a collection.

1. Iterating Over an Array:

let numbers = [1, 2, 3, 4, 5]

for number in numbers {
    print(number)
}
// Outputs:
// 1
// 2
// 3
// 4
// 5

2. Iterating Over a Dictionary:

let fruitColors: [String: String] = ["apple": "red", "banana": "yellow", "grape": "purple"]

for (fruit, color) in fruitColors {
    print("\(fruit) is \(color)")
}
// Outputs (order may vary because dictionaries are unordered):
// apple is red
// banana is yellow
// grape is purple

3. Iterating Over a Range:

for index in 1...5 {
    print(index)
}
// Outputs:
// 1
// 2
// 3
// 4
// 5

4. Iterating Over a String's Characters:

let word = "Swift"

for character in word {
    print(character)
}
// Outputs:
// S
// w
// i
// f
// t

5. Ignoring the Current Value:

If you don't need the current item of the sequence, you can use an underscore (_) to ignore it:

for _ in 1...3 {
    print("Hello")
}
// Outputs:
// Hello
// Hello
// Hello

6. Using Where to Filter Items:

You can use the where clause in a for-in loop to filter items:

let numbers = [1, 2, 3, 4, 5, 6]

for number in numbers where number % 2 == 0 {
    print(number)
}
// Outputs:
// 2
// 4
// 6

7. Nested for-in Loops:

You can nest for-in loops to iterate over multiple collections:

for i in 1...3 {
    for j in 1...3 {
        print("i: \(i), j: \(j)")
    }
}

In Summary:

The for-in loop in Swift is a versatile and essential construct for iteration. It offers a concise way to iterate over a wide variety of sequences and collections, making your code more readable and expressive.

  1. How to iterate over arrays with for-in in Swift:

    • Description: Use the for-in loop to iterate over elements in an array.

    • Code:

      let numbers = [1, 2, 3, 4, 5]
      
      for number in numbers {
          print(number)
      }
      
  2. Looping through dictionaries using for-in in Swift:

    • Description: for-in can iterate over key-value pairs in a dictionary.

    • Code:

      let person = ["name": "John", "age": 30, "city": "New York"]
      
      for (key, value) in person {
          print("\(key): \(value)")
      }
      
  3. Swift for-in loop with ranges:

    • Description: Ranges can be used with for-in loops to iterate over a specific range of values.

    • Code:

      for i in 1...5 {
          print(i)
      }
      
  4. Enumerating elements with for-in loop in Swift:

    • Description: The enumerated() method allows access to both the index and the value during iteration.

    • Code:

      let fruits = ["Apple", "Banana", "Orange"]
      
      for (index, fruit) in fruits.enumerated() {
          print("\(index): \(fruit)")
      }
      
  5. Using for-in to loop through strings in Swift:

    • Description: Strings can be iterated character by character using for-in.

    • Code:

      let message = "Hello, Swift!"
      
      for char in message {
          print(char)
      }
      
  6. Iterating over sets with for-in loop in Swift:

    • Description: Sets can be iterated using for-in to access unique elements.

    • Code:

      let uniqueNumbers: Set<Int> = [1, 2, 3, 2, 4]
      
      for number in uniqueNumbers {
          print(number)
      }
      
  7. Nested for-in loops in Swift:

    • Description: for-in loops can be nested to iterate over multiple levels of data.

    • Code:

      let matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
      
      for row in matrix {
          for element in row {
              print(element)
          }
      }
      
  8. Break and continue statements in Swift for-in loop:

    • Description: Use break to exit the loop and continue to skip to the next iteration.

    • Code:

      let numbers = [1, 2, 3, 4, 5]
      
      for number in numbers {
          if number == 3 {
              break // Exit the loop when number is 3
          }
          print(number)
      }