protocol Iterator {
associatedtype Element
func hasNext() -> Bool
func next() -> Element?
}
class ConcreteIterator<T>: Iterator {
typealias Element = T
private var collection: [T]
private var index = 0
init(_ collection: [T]) {
self.collection = collection
}
func hasNext() -> Bool {
return index < collection.count
}
// 순회 인터페이스 구현
func next() -> T? {
guard hasNext() else {
return nil
}
let element = collection[index]
index += 1
return element
}
}
// Aggregate가 필수일까?
protocol Aggregate {
associatedtype Element
func createIterator() -> ConcreteIterator<Element>
}
class ConcreteAggregate<T>: Aggregate {
typealias Element = T
private var items: [T]
init(_ items: [T]) {
self.items = items
}
func createIterator() -> ConcreteIterator<T> {
return ConcreteIterator<T>(items)
}
}
// 예제 데이터
let numbers = [1, 2, 3, 4, 5]
// ConcreteAggregate 인스턴스 생성
let numberAggregate = ConcreteAggregate(numbers)
// Iterator 생성
let iterator = numberAggregate.createIterator()
// Iterator를 사용하여 순회
while iterator.hasNext() {
if let number = iterator.next() {
print(number)
}
}
https://developer.apple.com/documentation/swift/iteratorprotocol
참고