I\'ve been running into an issue using Swift 2\'s protocol extensions with default implementations. The basic gist is that I\'ve provided a default implementation of a proto
Unfortunately protocols don't have such an dynamic behavior (yet).
But you can do that (with the help of classes) by implementing commonBehavior()
in the ParentClass
and overriding it in the ChildClass
. You also need CommonThing
or another class to conform to CommonTrait
which is then the superclass of ParentClass
:
class CommonThing: CommonTrait {
func say() -> String {
return "override this"
}
}
class ParentClass: CommonThing {
func commonBehavior() -> String {
// calling the protocol extension indirectly from the superclass
return (self as CommonThing).commonBehavior()
}
override func say() -> String {
// if called from ChildClass the overridden function gets called instead
return commonBehavior()
}
}
class AnotherParentClass: CommonThing {
override func say() -> String {
return commonBehavior()
}
}
class ChildClass: ParentClass {
override func say() -> String {
return super.say()
}
// explicitly override the function
override func commonBehavior() -> String {
return "from child class"
}
}
let parent = ParentClass()
parentClass.say() // "from protocol extension"
let child = ChildClass()
child.say() // "from child class"
Since this is only a short solution for your problem I hope it fits in your project.