Skip to content

Instantly share code, notes, and snippets.

@cmittendorf
Last active August 29, 2015 14:02
Show Gist options
  • Save cmittendorf/55fc656612f495dbe3f5 to your computer and use it in GitHub Desktop.
Save cmittendorf/55fc656612f495dbe3f5 to your computer and use it in GitHub Desktop.
Adds an each closure to Arrays in Swift.
#!/usr/bin/env xcrun swift -i
extension Array {
func each(closure:(T) -> ()) {
for item:T in self {
closure(item)
}
}
func eachWithIndex(closure:(Int, T) -> ()) {
var i:Int = 0
for item:T in self {
closure(i, item)
i++
}
}
}
println("program arguments:")
Process.arguments.eachWithIndex { (idx, arg) in
println("\(idx) : \(arg)")
}
println("my little farm:")
let a:[String] = ["Dog", "Cow", "Horse"]
a.each {
println($0)
}
println("I'm counting to…")
let b:[Int] = [1,2,3]
b.each { (item:Int) in
println(item)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment