카테고리 없음
[Swift] IteratorProtocol
윈컴이
2022. 12. 6. 02:06
protcol IteratorProtocol {
associatedtype Element
mutating func next() -> Element?
}
- IteratorProtocol은 Sequence 프로토콜과 강력히 연결되어있다.
- for-in 루프를 사용할 때 그 타입의 이터레이터를 사용한다. (예: Array, Set)
let animals = ["Antelope", "Butterfly", "Camel", "Dolphin"]
for animal in animals {
print(animal)
}
var animalIterator = animals.makeIterator() // Iterator 클래스 인스턴스 생성
while let animal = animalIterator.next() {
print(animal)
}
// 이터레이터 사용 후 _position이 변경되었기 때문에 재사용시 새로운 이터레이터 인스턴스를 생성해야함