Skip to content

Instantly share code, notes, and snippets.

@ketzusaka
Created July 17, 2015 16:44
Show Gist options
  • Select an option

  • Save ketzusaka/31ff86b8c2f73ce9c1e1 to your computer and use it in GitHub Desktop.

Select an option

Save ketzusaka/31ff86b8c2f73ce9c1e1 to your computer and use it in GitHub Desktop.
Generator-scoped variables
func anyGenerator<Element>(initial: Element, body: (inout Element) -> Element?) -> AnyGenerator<Element> {
return {
var i: Element? = initial
return anyGenerator {
var r: Element?
if var x = i {
r = body(&x)
i = x
}
return r
}
}()
}
let naturalNumbers = anyGenerator(0) { (inout a: Int) in
return a++
}
print(naturalNumbers.next()) // Prints Optional(0)
print(naturalNumbers.next()) // Prints Optional(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment