call a protected static method on an instance of a class in swift

In Swift, protected methods and properties are not accessible outside of the class or its subclasses. However, we can define a "helper" method inside the class that creates and returns an instance of that class, and then call the protected static method on it.

Here's an example:

main.swift
class MyClass {
    protected static func myMethod() {
        print("Hello, World!")
    }
    
    static func callProtectedMethodOnInstance() {
        let instance = MyClass()
        instance.dynamicType.myMethod()
    }
}

MyClass.callProtectedMethodOnInstance() // Outputs "Hello, World!"
296 chars
13 lines

In this example, we define a protected static method myMethod on the MyClass class. We also define a method callProtectedMethodOnInstance that creates an instance of MyClass and then calls myMethod on its dynamic type.

Note that we use dynamicType to get the type of the object at runtime, since instance is declared as a MyClass but may actually be an instance of a subclass that also defines myMethod.

gistlibby LogSnag