Last active
August 29, 2015 14:02
-
-
Save marklarr/cb6cbd25a6c486c45680 to your computer and use it in GitHub Desktop.
each.swift
This file contains 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
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