How to make an instance property only visible to subclass swift
SwiftAccess ControlSwift Problem Overview
I'm trying to declare a instance property in swift so that it is only visible to it's class and subclasses. I believe this would be referred to as a protected property in other languages. Is there a way to achieve this in Swift?
Swift Solutions
Solution 1 - 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 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.
There's further explanation on Apple's Swift blog.
Solution 2 - Swift
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.