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 Foundation

class Animal {
    fileprivate var protectedVar: Int = 0
}

class Dog: Animal {
    func doSomething() {
        protectedVar = 1
    }
}

OtherFile.swift

let dog = Dog()
dog.doSomething()