How to declare a 'protected' variable in swift How to declare a 'protected' variable in swift swift swift

How to declare a 'protected' variable in swift


You would have to use internal for that as Swift doesn't offer a protected keyword (unlike many other programming languages). internal is the only access modifier between fileprivate and public:

Internal access enables entities to be used within any source file from their defining module, but not in any source file outside of that module. You typically use internal access when defining an app’s or a framework’s internal structure.

There is a blog post that explains a little bit more about why the language designers chose not to offer a protected keyword (or anything equivalent).

Some of the reasons being that

It doesn’t actually offer any real protection, since a subclass can always expose “protected” API through a new public method or property.

and also the fact that protected would cause problems when it comes to extensions, as it wouldn't be clear whether extensions should also have access to protected properties or not.


Even if Swift doesn't provide protected access, still we can achieve similar access by using fileprivate access control.
Only thing we need to keep in mind that we need to declare all the children in same file as parent declared in.

Animal.swift

import Foundationclass Animal {    fileprivate var protectedVar: Int = 0}class Dog: Animal {    func doSomething() {        protectedVar = 1    }}

OtherFile.swift

let dog = Dog()dog.doSomething()


Use an underscore for such protected variables :/

That's about it ...

class RawDisplayThing {        var _fraction: CGFloat = 0 {        didSet { ... }    }class FlightMap: RawDisplayThing() {    var currentPosition() {        ...        _fraction =         ...    }}

Everyone has to "just agree" that only the concept class can use the "_" variables and functions.

At least, it's then relatively easy to search globally on each "_" item and ensure it only used by the superclasses.

Alternately, prepend say "local", "display", or possibly the name of the class (or whatever makes sense to your team) to such concepts.

class RawDisplayThing {        var rawDisplayFraction: ...    var rawDisplayTrigger: ...    var rawDisplayConvolution: ...

etc etc. Maybe it helps :/