Skip to content

Instantly share code, notes, and snippets.

@ilyapuchka
Last active October 29, 2015 11:44
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 ilyapuchka/89f81090c09d361596b6 to your computer and use it in GitHub Desktop.
Save ilyapuchka/89f81090c09d361596b6 to your computer and use it in GitHub Desktop.
Swift extensions for classes and structs
protocol ProtocolA {}
protocol ProtocolB: ProtocolA {}
protocol ProtocolC {
func act()
}
protocol ProtocolD {
typealias V
func act()
}
struct StructA: ProtocolA {}
struct StructB: ProtocolB {}
struct StructC<T: ProtocolA>: ProtocolC {}
extension StructC {
func act() {
print("general")
}
}
extension StructC where T: ProtocolB {
func act() {
print("special")
}
}
struct StructD<T: ProtocolA>: ProtocolD {
typealias V = T
}
extension ProtocolD {
func act() {
print("general")
}
}
extension ProtocolD where V: ProtocolB {
func act() {
print("special")
}
}
class ClassC<T: ProtocolA>: ProtocolC {
}
extension ClassC {
func act() {
print("general")
}
}
extension ClassC where T: ProtocolB {
func act() {
print("special")
}
}
let classCA = ClassC<StructA>()
let classCB = ClassC<StructB>()
//this works
classCA.act() //-> "general"
classCB.act() //-> "special"
let structCA = StructC<StructA>()
let structCB = StructC<StructB>()
//Does not even compile
structCA.act()
structCB.act() // error: "Ambigous use of 'act()'"
let structDA = StructD<StructA>()
let structDB = StructD<StructB>()
//works again
structDA.act() //-> "general"
structDB.act() //-> "special"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment