我正在实现一个协议(protocol)并在 swift 中提供一些可选方法,然后我在派生类中实现这些可选方法。当我调用协议(protocol)方法时,它调用的是扩展方法而不是派生类方法。
protocol ProtocolA {
func method1()
// Optional
func method2()
}
extension ProtocolA {
func method2(){
// It comes here, instead of class B method2.
print("In method 2 - Protocol A")
}
}
class A : ProtocolA {
func method1() {
print("In method 1 - class A")
}
}
class B : A {
func method2() {
print("In method 2 - Class B")
}
}
var a : A = B()
// It should call - In method 2 - Class B but the output is "In method 2 - Protocol A"
a.method2()
首先,您应该在类 A 上为类 B 实现方法,您可以覆盖该方法,例如:
protocol ProtocolA {
func method1()
// Optional
func method2()
}
extension ProtocolA {
func method2(){
// It comes here, instead of class B method2.
print("In method 2 - Protocol A")
}
}
class A : ProtocolA {
func method1() {
print("In method 1 - Class A")
}
func method2(){
// It comes here, instead of class B method2.
print("In method 2 - Class A")
}
}
class B : A {
override func method2() {
print("In method 2 - Class B")
}
}
var a : A = B()
a.method2()
或者直接使用 B 类作为 Type:
protocol ProtocolA {
func method1()
// Optional
func method2()
}
extension ProtocolA {
func method2(){
// It comes here, instead of class B method2.
print("In method 2 - Protocol A")
}
}
class A : ProtocolA {
func method1() {
print("In method 1 - Class A")
}
// func method2(){
// // It comes here, instead of class B method2.
// print("In method 2 - Class A")
// }
}
class B : A {
func method2() {
print("In method 2 - Class B")
}
}
var b : B = B()
b.method2()
问题是运行时选择基于变量类型实现的函数。