add a protected property to a class in swift

In Swift, we can add a protected property to a class by using the internal access level modifier. The internal access level allows the property to be accessed within the module but not from outside the module. Here's an example:

main.swift
class MyClass {
    internal var myProtectedProperty: String = "protected"
    
    func myFunc() {
        // myProtectedProperty is accessible within the class
        print(myProtectedProperty)
    }
}
205 chars
9 lines

In this example, we've added a protected property to the MyClass class using the internal access level modifier. The myProtectedProperty property can be accessed within MyClass and any other classes in the same module, but not from outside the module.

To access the protected property in a subclass, we can use the super keyword:

main.swift
class MySubclass: MyClass {
    func myOtherFunc() {
        // myProtectedProperty is accessible from a subclass
        print(super.myProtectedProperty)
    }
}
163 chars
7 lines

In this example, we're accessing the myProtectedProperty property from the MySubclass. The super keyword is used to access the property from the superclass.

gistlibby LogSnag