add a protected static property to a class in swift

To add a protected static property to a class in Swift, we can make use of access control keywords.

In Swift, the access control keywords are public, internal, fileprivate and private.

To make a property protected, we can mark it as fileprivate. Similarly, to make it static, we can use the static keyword.

Here's an example:

main.swift
class MyClass {
    fileprivate static var myProtectedProperty: Int = 10
}
75 chars
4 lines

In the above example, we added a fileprivate static property called myProtectedProperty to the MyClass class.

Since it's marked as fileprivate, it's only accessible within the same file. But subclasses of MyClass can access this property since they are in the same file.

We can access it from a subclass like this:

main.swift
class MySubclass: MyClass {
    func doSomething() {
        MyClass.myProtectedProperty = 20
    }
}
102 chars
6 lines

Note that if we mark the property as private, it will only be accessible within the same class, and not to the subclasses.

gistlibby LogSnag