加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift:如何将超类中的公共方法重写为子类中的私有方法

发布时间:2020-12-14 05:26:33 所属栏目:百科 来源:网络整理
导读:我有一个超级班 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 那么,
我有一个超级班
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

那么,如何覆盖超类中的公共方法是子类中的私有方法

谢谢

你不能,因为这会违反 Liskov Substitution Principle.

实质上,任何可以在超类实例上运行的代码也必须能够在子类的实例上运行.

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

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

当你执行以下操作时,它仍然需要工作:

let aChild = Child()

unrelatedInstance.operateOnAThing(aChild)

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读