Created
November 6, 2016 20:52
-
-
Save khanlou/22ed5f66be4c41910eef2bf658d8ec27 to your computer and use it in GitHub Desktop.
Ruby's n.times in Swift
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
| extension SignedInteger { | |
| func times() -> AnySequence<()> { | |
| return AnySequence<()>({ () -> AnyIterator<()> in | |
| var count: Self = 0 | |
| return AnyIterator<()>({ | |
| if count == self { | |
| return nil | |
| } | |
| defer { count = count + 1 } | |
| return () | |
| }) | |
| }) | |
| } | |
| func timesWithIndex() -> AnySequence<Self> { | |
| return AnySequence<Self>({ () -> AnyIterator<Self> in | |
| var count: Self = 0 | |
| return AnyIterator<Self>({ | |
| if count == self { | |
| return nil | |
| } | |
| defer { count = count + 1 } | |
| return count | |
| }) | |
| }) | |
| } | |
| } | |
| 5.times().forEach { | |
| print("hi") | |
| } | |
| 5.timesWithIndex().forEach { i in | |
| print("hey", i) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment