Last active
January 13, 2016 07:34
-
-
Save citizen428/05b2ebebb9b052b1bf04 to your computer and use it in GitHub Desktop.
Swift sequences, generators etc
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class EvenNumbers: CollectionType { | |
let startIndex : Int | |
let endIndex : Int | |
init(start: Int, end: Int) { | |
self.startIndex = start | |
self.endIndex = end | |
} | |
convenience init() { | |
let start = 0 | |
let end = Int.max | |
self.init(start: start, end: end) | |
} | |
func generate() -> AnyGenerator<Int> { | |
var current = 0 | |
return anyGenerator { | |
guard current <= self.endIndex else { return nil } | |
let oldCurrent = current | |
current += 1 | |
return self.nthEven(oldCurrent) | |
} | |
} | |
subscript(i: Int) -> Int { | |
assert(i >= 0) | |
return nthEven(i) | |
} | |
private func nthEven(n: Int) -> Int { | |
return n * 2 | |
} | |
} | |
let evens = EvenNumbers(start: 0, end: 6) | |
for x in evens { | |
print(x) | |
} | |
// 0 | |
// 2 | |
// 4 | |
// 6 | |
// 8 | |
// 10 | |
// 12 | |
evens[5] // 10 | |
evens[-1] // assertion failed: : file <EXPR>, line 28 | |
let evensGenerator = EvenNumbers().generate() | |
for i in 1...5 { | |
print(evensGenerator.next()) | |
} | |
// Optional(0) | |
// Optional(2) | |
// Optional(4) | |
// Optional(6) | |
// Optional(8) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment