swift - 未调用重写方法?

标签 swift

B 类是 A 类的子类 (B : A)

我将类初始化为 B.init()

当在 A 中调用时,覆盖 method( ) 永远不会被调用,除非我使用强制转换:

class A {
    ...
    self.method() //A method called
    (self as! B).method() //B method called
}

为什么?

由于我将实例初始化为 B,我希望它会调用重写方法,但事实并非如此,除非我使用强制转换。

最佳答案

我认为你在幕后有一些错误。我构建了您的示例,它按预期工作:

class A {
    func method() {
        print("A")
    }
    func check() {
        method()
        (self as? B)?.method()
    }
}
class B: A {
    override func method() {
        print("B")
    }
}

其他地方:

let b = B()
b.check()
//B
//B

关于swift - 未调用重写方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38996783/

相关文章:

ios - 从后台返回后,Alamofire 进度回调停止工作

ios - 使图像适合圆形 ImageView

swift - 为什么 SKSpriteNode 不能与 SKAction 一起使用?

ios - 当外设需要特殊 ACK 时,CoreBluetooth 和状态保存和恢复

ios - 重命名 View Controller 后 xcode iOS 应用程序崩溃

ios - 如何快速在启动屏幕中播放音频文件

ios - 检查倒计时是否已为零并更新 UILabel

ios - CAMediaTimingFunction 与不透明动画

swift - 一键式 SCNAction?

ios - 使用 Swift 3 下载网页内容