GoF의 디자인 패턴, 반복자 패턴에 대해 알아본다.
해당 글은, 다음의 코드를 기반으로 이해하는 것이 편리합니다.
import Foundation
internal func main() {
let items = [
Item(name: "Bitcoin", cost: 23000),
Item(name: "Tesla", cost: 170),
Item(name: "Jordan", cost: 200),
Item(name: "CyberTruck", cost: 50000)
]
let array = Array(items: items)
let iterator = array.iterator
while iterator.next {
guard let current = iterator.current as? Item else {
break
}
print(current.description)
}
}
main()
import Foundation
internal protocol Object {
}
import Foundation
internal protocol Aggregator {
var iterator: Iterator { get }
}
import Foundation
internal protocol Iterator {
var next: Bool { get }
var current: Object? { get }
}
import Foundation
internal protocol Loggable {
var description: String { get }
}
import Foundation
internal class Item: Object {
internal init(name: String, cost: Int) {
self.name = name
self.cost = cost
}
private let name: String
private let cost: Int
}
import Foundation
internal class Array: Aggregator, Object {
internal init(items: [Item]) {
self.items = items
}
internal var iterator: Iterator {
ArrayIterator(array: self)
}
internal var count: Int {
self.items.count
}
internal func item(at index: Int) -> Item? {
guard index < self.items.count else {
return nil
}
return self.items[index]
}
private var items = [Item]()
}
import Foundation
internal class ArrayIterator: Iterator {
internal var next: Bool {
self.index += 1
return self.index < self.array.count
}
internal var current: Object? {
self.array.item(at: self.index)
}
internal init(array: Array) {
self.array = array
self.index = -1
}
private var array: Array
private var index: Int
}