Swift 디자인패턴 Iterator Pattern (반복자 패턴)
Swift 디자인패턴 Iterator Pattern (반복자 패턴)
Iterator Pattern은 컬렉션(집합체)에 저장된 요소를 순차적으로 접근하는 방법을 제공하는 행동 디자인 패턴.
컬렉션의 내부 구현 방식을 노출하지 내부 요소들은 탐색할 수 있도록 함.
히스토리
- 2022-05-13: 디자인 패턴 스터디 정리
- 2024-11-28: 포스팅 글 재정리 및 조금 더 실용적인 예제 코드로 변경
Iteractor Pattern
두 가지 개념으로 구성됨
- Iterator: 컬렉션의 요소를 하나씩 탐색하는 객체. 주로 next(), hasNext() 같은 메서드를 제공.
- Iterable: 반복자 객체를 반환하는 makeIterator() 메서드를 제공하여, 컬렉션이 반복 가능하도록 함.
이터레이터 패턴 장점
- 컬렉션 내부 구현을 은닉하면서 요소를 순회 가능
- 여러 이터레이터 구현을 통해 다양한 탐색 방법 제공
- SRP 원칙 준수: 컬렉션과 탐색 로직 분리
이터페이터 패턴 단점
- 반복자 별도로 구현해야 해서 복잡성 증가
- 컬렉션 크기가 클 경우 메모리 관리에 주의
적용하면 좋은 경우
- 정방향, 역방향, 조건부 탐색 등 다양한 순회 방법 제공하고자 할 때
코드 예제
IteratorProtocol 및 Sequence를 활용해 Array를 구현해 볼 예정
import SwiftUI
struct ArrayIterator<T>: IteratorProtocol {
private let items: [T]
private var index = 0
init(items: [T]) {
self.items = items
}
mutating func next() -> T? {
guard index < items.count else { return nil }
defer { index += 1 }
return items[index]
}
}
struct CustomCollection<T>: Sequence {
private var items: [T] = []
mutating func addItem(_ item: T) {
items.append(item)
}
func makeIterator() -> ArrayIterator<T> {
return ArrayIterator(items: items)
}
}
private struct ContentView: View {
var body: some View {
Button("Execute") {
var collection = CustomCollection<String>()
collection.addItem("Apple")
collection.addItem("Banana")
collection.addItem("Cherry")
for item in collection {
print(item)
}
}
}
}
#Preview {
ContentView()
}
(참고)
https://www.raywenderlich.com/books/design-patterns-by-tutorials/v3.0/chapters/13-iterator-pattern
Design Patterns by Tutorials, Chapter 13: Iterator Pattern
The iterator pattern provides a standard way to loop through a collection. Use the iterator pattern when you have a class or struct that holds a group of ordered objects, and you want to make it iterable using a “for in” loop.
www.kodeco.com:443
https://refactoring.guru/ko/design-patterns/iterator
반복자 패턴
/ 디자인 패턴들 / 행동 패턴 반복자 패턴 다음 이름으로도 불립니다: Iterator 의도 반복자는 컬렉션의 요소들의 기본 표현(리스트, 스택, 트리 등)을 노출하지 않고 그들을 하나씩 순회할 수
refactoring.guru