Created
June 26, 2014 00:55
-
-
Save iamvery/10e5594daf6783117c3d to your computer and use it in GitHub Desktop.
swift generic type constraints
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
protocol Foobery { | |
func asFoo() -> String | |
} | |
extension String: Foobery { | |
func asFoo() -> String { | |
return "foo" | |
} | |
} | |
extension Int: Foobery { | |
func asFoo() -> String { | |
return "bar" | |
} | |
} | |
struct Stack<T: Foobery> { | |
var collection = T[]() | |
mutating func push(item: T) { | |
collection.append(item) | |
} | |
mutating func pop() -> T { | |
return collection.removeLast() | |
} | |
} | |
var stack = Stack<String>() | |
stack.push("first") | |
stack.push("second") | |
let second = stack.pop() | |
second.asFoo() | |
stack.pop() | |
stack | |
struct Ztack { | |
var collection = Array<Foobery>() | |
mutating func push(item: Foobery) { | |
collection.append(item) | |
} | |
mutating func pop() -> Foobery { | |
return collection.removeLast() | |
} | |
} | |
var ztack = Ztack() | |
ztack.push("first") | |
ztack.push("second") | |
ztack.push(123) | |
let zhird = ztack.pop() | |
zhird.asFoo() | |
let zecond = ztack.pop() | |
zecond.asFoo() | |
ztack.pop() | |
ztack |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment