Skip to content

Commit eb69fb9

Browse files
author
Sebastian Boldt
committed
Implemented Iterator Pattern
1 parent 26c2f90 commit eb69fb9

File tree

4 files changed

+45
-4
lines changed

4 files changed

+45
-4
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
//: [Previous](@previous)
2+
3+
import Foundation
4+
5+
public struct Book {
6+
var name : String
7+
}
8+
9+
public struct Library {
10+
var catalog = [Book]()
11+
}
12+
13+
public struct LibraryIterator : IteratorProtocol {
14+
15+
public var lib : Library
16+
private var currentIndex : Int = 0
17+
18+
public init(lib: Library) {
19+
self.lib = lib
20+
}
21+
22+
mutating public func next() -> Book? {
23+
defer{ currentIndex = currentIndex + 1}
24+
return currentIndex >= lib.catalog.count ? nil : lib.catalog[currentIndex]
25+
}
26+
}
27+
28+
extension Library : Sequence {
29+
public func makeIterator() -> LibraryIterator {
30+
return LibraryIterator(lib:self)
31+
}
32+
}
33+
34+
35+
let catalog = [Book(name:"Bla"),Book(name:"Blub"),Book(name:"Foo")]
36+
let library = Library(catalog: catalog)
37+
38+
for book in library {
39+
print(book.name)
40+
}
41+
//: [Next](@next)
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2-
<playground version='6.0' target-platform='ios' display-mode='raw'>
2+
<playground version='6.0' target-platform='ios' display-mode='raw' executeOnSourceChanges='false'>
33
<pages>
4-
<page name='Intro'/>
54
<page name='Chain of Responsibility '/>
65
<page name='Command'/>
6+
<page name='Iterator'/>
77
</pages>
88
</playground>

β€ŽREADME.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,13 @@ Inspired by: https://github.com/ochococo/Design-Patterns-In-Swift
1111

1212
* βœ… Chain Of Responsibility
1313
* βœ… Command
14+
* βœ… Iterator
15+
* ❌ Strategy
1416
* ❌ Interpreter
15-
* ❌ Iterator
1617
* ❌ Mediator
1718
* ❌ Memento
1819
* ❌ Observer
1920
* ❌ State
20-
* ❌ Strategy
2121
* ❌ Visitor
2222

2323
##Creational

0 commit comments

Comments
Β (0)