swift:如何将父类(super class)中的公共(public)方法覆盖为子类中的私有(private)方法

标签 swift inheritance

我有一个 super 类(class)

class Father {
    public func doSomething() {
    } 
}

我希望这个子类是

class Child: Father {
    private override func doSomething() {
    }
}

但是 Xcode 是这么说的

Overriding instance method must be as accessible as the declaration it overrides

那么,如何将父类(super class)中的公共(public)方法覆盖为子类中的私有(private)方法

谢谢

最佳答案

你不能因为那样会违反 Liskov Substitution Principle .

本质上,任何可以对父类(super class)的实例进行操作的代码也必须能够对子类的实例进行操作。

所以,如果其他一些类有一个方法

class Unrelated {
    func operateOnAThing(_ someThing:Father) {
        someThing.doSomething()
    }
}

然后当您执行以下操作时它仍然必须工作:

let aChild = Child()

unrelatedInstance.operateOnAThing(aChild)

如果 doSomething 方法在 Child 类中具有更严格的访问权限,那么您将遇到运行时错误。为防止这种情况,您不能在子类中对访问进行更严格的限制。

关于swift:如何将父类(super class)中的公共(public)方法覆盖为子类中的私有(private)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36660635/

相关文章:

Javascript 继承与揭示原型(prototype)设计模式

c++ - vector 指针,继承

ios - iAd 使用模拟器时出错

mysql - Json feed blob 图像在 UIImage swift 中显示

c++ - 从 C++ 中的 "interface"访问派生类成员?

c++ - 惰性构造 - 虚拟方法与 if-then stub setter/getter

Java浅拷贝子类实例的父类(super class)实例

ios - 如何在 ModelIO MDLMesh 和 SceneKit SCNGeometry 之间来回转换?

Swift Google map GMS 标记未粘贴在用户位置上

ios - TableView 调整父 View 大小 iOS