How to make an instance property only visible to subclass swift

SwiftAccess Control

Swift 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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnwalesView Question on Stackoverflow
Solution 1 - SwiftricksterView Answer on Stackoverflow
Solution 2 - Swiftfunct7View Answer on Stackoverflow