Skip to content

Instantly share code, notes, and snippets.

@iamvery
Created June 26, 2014 00:55
Show Gist options
  • Save iamvery/10e5594daf6783117c3d to your computer and use it in GitHub Desktop.
Save iamvery/10e5594daf6783117c3d to your computer and use it in GitHub Desktop.
swift generic type constraints
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