Last active
August 29, 2015 14:16
-
-
Save CanTheAlmighty/475448fde1c78cca014c to your computer and use it in GitHub Desktop.
Swift Rubyisms
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 Int | |
| { | |
| func times(f :(Int) -> ()) | |
| { | |
| for i in 0..<self | |
| { | |
| f(i) | |
| } | |
| } | |
| } | |
| extension Array | |
| { | |
| func each(f :(T) -> ()) | |
| { | |
| for item in self | |
| { | |
| f(item) | |
| } | |
| } | |
| } | |
| extension Range | |
| { | |
| func each(f :(T) -> ()) | |
| { | |
| for item in self | |
| { | |
| f(item) | |
| } | |
| } | |
| } | |
| // Repeat N times | |
| 5.times { println("Called \($0+1) times") } | |
| // Simple each-do cycle | |
| ["Dog", "Cat", "Parrot"].each { println($0) } | |
| // Each-do for Range<T> | |
| // (Unfortunately, it needs the parenthesis, otherwise the compiler complaints) | |
| (0..<4).each { println("\($0)") } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I didn't expect that you can get the
Tgeneric type from the Array in the extension, but it actually works (at least on Swift 1.2).