Ho avuto un problema con le estensioni del protocollo di Swift 2 con le implementazioni predefinite. L'essenziale è che ho fornito un'implementazione predefinita di un metodo di protocollo che sto scavalcando in una classe che implementa il protocollo. Quel metodo di estensione del protocollo viene chiamato da una classe base, che chiama quindi un metodo che ho sovrascritto in una classe derivata. Il risultato è che il metodo sottoposto a override non viene chiamato.Estensione del protocollo Swift 2 che non chiama correttamente il metodo sovrascritto
Ho provato a distillare il problema nel campo più piccolo possibile che illustra il problema di seguito.
protocol CommonTrait: class {
func commonBehavior() -> String
}
extension CommonTrait {
func commonBehavior() -> String {
return "from protocol extension"
}
}
class CommonThing {
func say() -> String {
return "override this"
}
}
class ParentClass: CommonThing, CommonTrait {
override func say() -> String {
return commonBehavior()
}
}
class AnotherParentClass: CommonThing, CommonTrait {
override func say() -> String {
return commonBehavior()
}
}
class ChildClass: ParentClass {
override func say() -> String {
return super.say()
// it works if it calls `commonBehavior` here and not call `super.say()`, but I don't want to do that as there are things in the base class I don't want to have to duplicate here.
}
func commonBehavior() -> String {
return "from child class"
}
}
let child = ChildClass()
child.say() // want to see "from child class" but it's "from protocol extension”
vi consiglio di leggere questo post qui per capire come funziona: http://nomothetis.svbtle.com/the-ghost-of-swift-bugs-future – DevAndArtist