Created
July 17, 2015 16:44
-
-
Save ketzusaka/31ff86b8c2f73ce9c1e1 to your computer and use it in GitHub Desktop.
Generator-scoped variables
This file contains hidden or 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
| 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