Skip to content

Instantly share code, notes, and snippets.

@pgorzelany
Last active January 15, 2016 19:06
Show Gist options
  • Select an option

  • Save pgorzelany/5e0310cc969c36c862cb to your computer and use it in GitHub Desktop.

Select an option

Save pgorzelany/5e0310cc969c36c862cb to your computer and use it in GitHub Desktop.
Shows the edge cases of protocol extension and implementation in Swift
// Protocol defines a mandatory function
protocol FooType {
func introduce() -> Void
}
// Default implementation of the protocol requirement
extension FooType {
func introduce() {
print("This is the FooType")
}
}
// Protocol does not require anything
protocol BarType {
}
// Default implmenetation of function not required in protocol
extension BarType {
func introduce() {
print("This is the BarType")
}
}
class FooClass: FooType {
func introduce() {
print("This is the FooClass")
}
}
class BarClass: BarType {
func introduce() {
print("This is the BarClass")
}
}
let fooClass: FooClass = FooClass()
let fooClassType: FooType = FooClass()
fooClass.introduce() //This is the FooClass
fooClassType.introduce() //This is the FooClass
let barClass: BarClass = BarClass()
let barClassType: BarType = BarClass()
barClass.introduce() // This is the BarClass
barClassType.introduce() // This is the BarType
// Unexpectedly, even though barClassType is an instance of BarClass(),
// and the BarClass provided its own implementation of the introduce method,
// the default protocol implementation is still called.
// This only happens if we set the barClassType to be a BarType type
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment