Skip to content

Instantly share code, notes, and snippets.

@marklarr
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marklarr/cb6cbd25a6c486c45680 to your computer and use it in GitHub Desktop.
Save marklarr/cb6cbd25a6c486c45680 to your computer and use it in GitHub Desktop.
each.swift
import Foundation
protocol Enumerable {
typealias Element
func each( (Element) -> Void)
}
//-----------------------------
class Stack<T> : Enumerable {
typealias Element = T
var array: T[] = []
func push(a: T) {
array.append(a)
}
func pop() -> T {
return array.removeLast()
}
func each(iterBlock: (T) -> Void) {
for item in array.reverse() {
iterBlock(item)
}
}
}
//-----------------------------
var s = Stack<String>()
s.push("... Bye")
s.push("World")
s.push("Hello")
s.each { a in
println(a)
}
//-----------------------------
extension String : Enumerable {
typealias Element = Character
func each(iterBlock: (Character) -> Void) {
for char in self {
iterBlock(char)
}
}
}
"Hello".each { c in
println(c)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment