如何使实例 属性 仅对子类 swift 可见

How to make an instance property only visible to subclass swift

我正在尝试在 swift 中声明一个实例 属性,以便它仅对 class 和子 class 可见。我相信这在其他语言中会被称为受保护的 属性。在 Swift 中有没有办法实现这一点?

沿继承线的访问控制并不真正符合 Swift 和 Cocoa 背后的设计理念:

When designing access control levels in Swift, we considered two main use cases:

  • keep private details of a class hidden from the rest of the app
  • keep internal details of a framework hidden from the client app

These correspond to private and internal levels of access, respectively.

In contrast, protected conflates access with inheritance, adding an entirely new control axis to reason about. It doesn’t actually offer any real protection, since a subclass can always expose “protected” API through a new public method or property. It doesn’t offer additional optimization opportunities either, since new overrides can come from anywhere. And it’s unnecessarily restrictive — it allows subclasses, but not any of the subclass’s helpers, to access something.

还有进一步的解释on Apple's Swift blog

一种方法是使用 fileprivate 关键字定义函数或 属性 并在同一文件中定义子类,如下所示:

class Parent {
    fileprivate var someProperty: Any?
}

class Child: Parent {
    func someFunction() {
        print(someProperty)
    }
}

当然这很烦人,因为那个文件会很乱。更不用说为什么 Swift 允许这个但 protected 不允许只是... argh.