How to make an instance property only visible to subclass swift
Access control along inheritance lines doesn't really fit with the design philosophies behind Swift and 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 appThese correspond to
private
andinternal
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.
There's further explanation on Apple's Swift blog.
One way to do it is define the function or property with fileprivate
keyword and define the subclass in the same file like so:
class Parent { fileprivate var someProperty: Any?}class Child: Parent { func someFunction() { print(someProperty) }}
Of course this is super annoying, since that file will be a huge mess. Not to mention why Swift allows this but not protected
is just... argh.