ios - 扩展不会 swift 进入派生类

标签 ios swift swift2

<分区>

我正在实现一个协议(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()

问题是运行时选择基于变量类型实现的函数。

关于ios - 扩展不会 swift 进入派生类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34553612/

相关文章:

ios - 在 Swift 中检测可用的 API iOS 与 watchOS

ios - 如何在没有 IB 的情况下将 2 个按钮添加到右侧的 UINavigationbar?

ios - Xcode 7、iOS 9 和 Swift 2.0 让 ViewController 的生命周期变得很奇怪

swift - 如何从具有同名嵌套类型的类中引用全局类型?

iOS - Alamofire v2 Basic Auth 不工作

ios - 隐藏 tableView.tableFooterView 导致我的部分 headerView 消失

iphone - 接收者类型 *** 例如消息是前向声明

swift - [weak self] 情况下的快捷闭包语法

ios - Swift 可选链在闭包中不起作用

uiviewcontroller - 在 Swift 中使用新数据刷新 UIViewController