Skip to content

Instantly share code, notes, and snippets.

@citizen428
Last active January 13, 2016 07:34
Show Gist options
  • Save citizen428/05b2ebebb9b052b1bf04 to your computer and use it in GitHub Desktop.
Save citizen428/05b2ebebb9b052b1bf04 to your computer and use it in GitHub Desktop.
Swift sequences, generators etc
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