我想知道爲什麼以下不打印出我認爲應該。協議擴展和子類
/* Fails */
protocol TheProtocol {
func update()
}
class A: TheProtocol {
}
class B : A {}
extension TheProtocol {
func update() {
print("Called update from TheProtocol")
}
}
extension TheProtocol where Self: B {
func update() {
print("Called update from B")
}
}
let instanceB = B()
instanceB.update()
let instanceBViaProtocol:TheProtocol = B()
instanceBViaProtocol.update()
這將打印以下內容:
Called update from B
Called update from TheProtocol // Why not: Called update from B (extension)
我特別想知道爲什麼
instanceBViaProtocol.update()
不執行更新()在擴展上TheProtocol:
extension TheProtocol where Self: B {
func update() {
print("Called update from B")
}
}
我會認爲它會由於B是從採用TheProtocol的A繼承的,所以我認爲B會隱含地採用TheProtocol。 將協議採用從A移到B產生預期的結果。
protocol TheProtocol {
func update()
}
class A { // Remove TheProtocol
}
class B : A, TheProtocol {} // Add TheProtocol
extension TheProtocol {
func update() {
print("Called update from TheProtocol")
}
}
extension TheProtocol where Self: B {
func update() {
print("Called update from B")
}
}
let instanceB = B()
instanceB.update()
let instanceBViaProtocol:TheProtocol = B()
instanceBViaProtocol.update()
結果:
Called update from B
Called update from B
我看了看https://medium.com/ios-os-x-development/swift-protocol-extension-method-dispatch-6a6bf270ba94#.6cm4oqaq1和http://krakendev.io/blog/subclassing-can-suck-and-heres-why,但我無法想出解決辦法。擴展方法是否不符合採用該協議的實體的子類?
更改'擴展TheProtocol where Self:B {'to'extension TheProtocol where Self:A {'看看它是否解釋給你。 –
感謝您的提示。 – user6902806