Sobes.tech
Junior

How can you iterate over a collection?

sobes.tech AI

Answer from AI

Iterating over collections can be done in several ways, depending on the type of collection, the required functionality, and the coding style.

  1. for-in loop: The most common and versatile method for most collections.

    // Iterating over an array
    let numbers = [1, 2, 3, 4, 5]
    for number in numbers {
        print(number)
    }
    
    // Iterating over a dictionary (key-value pairs)
    let ages = ["Alice": 30, "Bob": 25]
    for (name, age) in ages {
        print("\(name) is \(age) years old.")
    }
    
  2. forEach method: A higher-order method available on most collections. It allows performing an action for each element.

    let fruits = ["Apple", "Banana", "Cherry"]
    fruits.forEach { fruit in
        print(fruit)
    }
    
  3. Iterating by index (for collections with indices, such as Array):

    let colors = ["Red", "Green", "Blue"]
    for i in 0..<colors.count {
        print("Color at index \(i) is \(colors[i])")
    }
    
  4. Using enumerated(): Allows obtaining both index and element during iteration.

    let animals = ["Dog", "Cat", "Bird"]
    for (index, animal) in animals.enumerated() {
        print("Animal at index \(index) is \(animal)")
    }
    
  5. Iteration using an iterator (IteratorProtocol): A lower-level method suitable for creating custom collections or working with lazy sequences.

    struct Countdown: Sequence, IteratorProtocol {
        var count: Int
    
        // IteratorProtocol requires next()
        mutating func next() -> Int? {
            if count > 0 {
                count -= 1
                return count
            } else {
                return nil
            }
        }
    
        // Sequence requires makeIterator()
        func makeIterator() -> Countdown {
            return self
        }
    }
    
    let countdown = Countdown(count: 3)
    for number in countdown {
        print(number) // Outputs 2, 1, 0
    }
    

The choice of method depends on the context: for-in is the most common, forEach is often used for simple actions, iterating by index is useful when the index is needed, and enumerated() is convenient when both index and value are needed. Using IteratorProtocol is necessary when creating custom types that implement the Sequence protocol.

How can you iterate over a collection? — iOS - sobes.tech