다음과 같은 이유가 인쇄되어 있지 않은 이유가 궁금합니다.프로토콜 확장명 및 서브 클래스
/* 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 어디서 Self : B {'에서'확장 기능 TheProtocol where Self : A {'그리고 당신에게 뭔가 설명하는지보십시오. –
팁 주셔서 감사. – user6902806