-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathgenerators.swift
49 lines (37 loc) · 1002 Bytes
/
generators.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
import Foundation
// `GeneratorType` is a type of `SequenceType`.
// In order to conform, set the Element
// typealias and implement the `next`
// method.
class Incrementing : GeneratorType {
typealias Element = Int
var counter = 0
func next() -> Element? {
return counter++
}
}
var count = Incrementing()
count.next()! // 0
count.next()! // 1
// `for` loops work with any `SequenceType` type.
// A `SequenceType` has a `generate` method that
// returns a `GeneratorType`.
class Fibonacci : SequenceType {
func generate() -> GeneratorOf<Int> {
var current = 0
var next = 1
return GeneratorOf<Int> {
var returnVal = current
current = next
next += returnVal
return returnVal
}
}
}
var fibSequence = Fibonacci()
for i in fibSequence {
if i > 50 {
break
}
print("\(i) ") // 0 1 1 2 3 5 8 13 21 34
}