Skip to content

Instantly share code, notes, and snippets.

@CanTheAlmighty
Last active August 29, 2015 14:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CanTheAlmighty/475448fde1c78cca014c to your computer and use it in GitHub Desktop.
Save CanTheAlmighty/475448fde1c78cca014c to your computer and use it in GitHub Desktop.
Swift Rubyisms
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)") }
@CanTheAlmighty
Copy link
Author

I didn't expect that you can get the T generic type from the Array in the extension, but it actually works (at least on Swift 1.2).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment