-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathIterator.Swift
102 lines (73 loc) · 1.73 KB
/
Iterator.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
//
// Created by Kenan Atmaca
// kenanatmaca.com
//
class Human {
var name:String
var surname:String
init(name:String,surname:String) {
self.name = name
self.surname = surname
}
}
protocol HumanIterator {
func next() -> Human?
func curentItem() -> Human?
func isDone() -> Bool
var count:Int {get}
}
protocol Aggregate {
func getIterator() -> HumanIterator
func getItem(_ index:Int) -> Human
}
class HumanAggregate: Aggregate {
private var list:[Human] = []
var count:Int {
return list.count
}
func add(_ h:Human) {
list.append(h)
}
func pop() {
if count > 0 {
list.removeLast()
}
}
func getItem(_ index:Int) -> Human {
return list[index]
}
func getIterator() -> HumanIterator {
return Iterator(self)
}
}
class Iterator: HumanIterator {
private var list:HumanAggregate
var index:Int = 0
var count:Int {
return list.count
}
init(_ list:HumanAggregate) {
self.list = list
}
func next() -> Human? {
defer {
index = index + 1
}
return isDone() ? list.getItem(index) : nil
}
func curentItem() -> Human? {
return list.getItem(index)
}
func isDone() -> Bool {
return index < count
}
}
let hum = HumanAggregate()
hum.add(Human(name: "Kenan", surname: "Atmaca"))
hum.add(Human(name: "John", surname: "Wick"))
hum.add(Human(name: "David", surname: "Cop"))
let makeIterator = hum.getIterator()
while makeIterator.isDone() {
print((makeIterator.curentItem()?.name)!)
makeIterator.next()
}