Sobes.tech
Junior — Middle

In what scenarios can the Iterable interface be used in your project?

sobes.tech AI

Answer from AI

The Iterable interface in Swift is used for objects that can be traversed in a loop (e.g., for-in). It is useful when you need to implement your own collection or data structure that supports iteration.

Use cases:

  • Creating custom collections, such as linked lists or trees, that can be iterated over.
  • Providing support for for-in loops for your types.
  • Implementing lazy sequences where elements are computed as they are iterated.

Example of a simple iterator implementation:

struct Countdown: Iterable {
    let start: Int

    func makeIterator() -> some IteratorProtocol {
        var current = start
        return AnyIterator {
            if current <= 0 {
                return nil
            } else {
                defer { current -= 1 }
                return current
            }
        }
    }
}

for number in Countdown(start: 3) {
    print(number) // 3, 2, 1
}

Thus, Iterable allows creating convenient and understandable interfaces for data traversal.