-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathIteratorPattern.swift
42 lines (33 loc) · 1.07 KB
/
IteratorPattern.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// The iterator pattern is used to provide a standard interface
// for traversing a collection of items in an aggregate object
// without the need to understand its underlying structure.
struct Novella {
let name: String
}
struct Novellas {
let novellas: [Novella]
}
struct NovellasIterator: IteratorProtocol {
private var current = 0
private let novellas: [Novella]
init(novellas: [Novella]) {
self.novellas = novellas
}
mutating func next() -> Novella? {
defer { current += 1 }
return novellas.count > current ? novellas[current] : nil
}
}
extension Novellas: Sequence {
func makeIterator() -> NovellasIterator {
return NovellasIterator(novellas: novellas)
}
}
// Usage
let greatNovellas = Novellas(novellas: [Novella(name: "The Mist 1"),
Novella(name: "The Mist 2"),
Novella(name: "The Mist 3"),
Novella(name: "The Mist 4")] )
for novella in greatNovellas {
print("I've read: \(novella)")
}