call a protected property on an instance of a class in swift

In Swift, calling a protected property on an instance of a class requires that the instance be accessed from within a subclass of that class. To do so, the keyword super must be used to specify the subclass, and then the protected property can be accessed using its name.

Here's an example:

main.swift
class MyBaseClass {
    protected var myProtectedProperty = "Hello, world!"
}

class MySubClass: MyBaseClass {
    func printMyProtectedProperty() {
        print(super.myProtectedProperty)
    }
}

let mySubClassInstance = MySubClass()
mySubClassInstance.printMyProtectedProperty() // Output: "Hello, world!"
310 chars
13 lines

In this example, we have two classes: MyBaseClass and MySubClass. The MyBaseClass contains a protected property myProtectedProperty, while the MySubClass inherits from the MyBaseClass. The MySubClass contains a method printMyProtectedProperty, which accesses the myProtectedProperty using the super keyword.

Note that if you try to access the protected property directly from an instance of MyBaseClass, you will get a compile-time error: " 'myProtectedProperty' is inaccessible due to 'protected' protection level".

gistlibby LogSnag