Skip to content

Instantly share code, notes, and snippets.

@yao2030
Created June 24, 2014 02:03
Show Gist options
  • Save yao2030/db079623905e29c4ec44 to your computer and use it in GitHub Desktop.
Save yao2030/db079623905e29c4ec44 to your computer and use it in GitHub Desktop.
extension Int {
func times(block: () -> ()) {
for _ in 0..self {
block()
}
}
func times(block: (Int) -> ()) -> Int {
for i in 0..self {
block(i)
}
return self
}
}
3.times { print("Ho, ") }
var x = 5.times {(i: Int) in println("Iteration \(i)") }
extension Array {
func each(block: (T -> ())) -> Array<T> {
for item in self {
block(item)
}
return self
}
}
var y = ["Hello", "World"].each { house in println("House \(house)")}
extension Dictionary {
func eachPair(block: (KeyType, ValueType) -> ()) -> Dictionary<KeyType, ValueType> {
for (key, val) in self {
block(key, val)
}
return self
}
}
let mealPlan = [ "breakfast": "pancakes", "lunch": "burrito", "dinner": "steak"]
mealPlan.eachPair {
meal, item in println("Having \(meal) for \(item)")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment