Skip to content

Instantly share code, notes, and snippets.

@plumhead
Created June 17, 2014 21:11
Show Gist options
  • Save plumhead/5b02c6eb08c03a266d44 to your computer and use it in GitHub Desktop.
Save plumhead/5b02c6eb08c03a266d44 to your computer and use it in GitHub Desktop.
Custom Sequence
class Times2Generator : Generator {
typealias Element = (original: Int,timestwo: Int)?
func next() -> Element? {
if source.count > 0 {
let result = self.source[0]
source = Array(source[1..source.count])
return (result,result * 2)
}
else {
return .None
}
}
init(s: Int[]) { self.source = s }
var source : Array<Int>!
}
class Times2Sequence : Sequence {
var values : Array<Int>
init(v : Array<Int>) {self.values = v}
// typealias can be inferred so could be left out
typealias GeneratorType = Times2Generator
func generate() -> Times2Generator {
return Times2Generator(s: values)
}
}
let ms = Times2Sequence(v: [1,2,5,10,20])
typealias T = Times2Sequence.GeneratorType.Element
for timesTwo : T in ms {
let (x,y) = timesTwo!
println("\(x) * 2 is \(y)")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment