-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path07-Composite.swift
48 lines (37 loc) · 1.13 KB
/
07-Composite.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
// Consider the code presented below. The 'sum()' extension method adds up all the values
// in a list of 'Sequence' - conforming elements it gets passed. We can have a single value
// or a set of values, all of them get added up toghether.
//
// Please complete the implementation of the extension so that 'sum()' begins to work correctly.
import Foundation
class SingleValue : Sequence {
var value = 0
init() {}
init(_ value: Int) {
self.value = value
}
func makeIterator() -> IndexingIterator<Array<Int>> {
return IndexingIterator(_elements: [value])
}
}
class ManyValues : Sequence {
var values = [Int]()
func makeIterator() -> IndexingIterator<Array<Int>> {
return IndexingIterator(_elements: values)
}
func add(_ value: Int) {
values.append(value)
}
}
// Solution
extension Sequence where Iterator.Element: Sequence, Iterator.Element.Iterator.Element == Int {
func sum() -> Int {
var result: Int = 0
for element in self {
for value in element {
result += value
}
}
return result
}
}