add a private method to a class in swift

In Swift, you can add a private method to a class by prefixing the method's definition with the private keyword. Private methods can only be called within the class that declares them.

Here's an example:

main.swift
class MyClass {
    
    private func myPrivateMethod() {
        // code here
    }
    
    func myPublicMethod() {
        // code here
        myPrivateMethod() // calling private method within the class
    }
    
}
221 chars
13 lines

In this example, myPrivateMethod() is defined as a private method within the MyClass. It can only be called within the MyClass.

myPublicMethod() is defined as a public method and can be called outside of MyClass. It can also call the private method myPrivateMethod() within the class.

gistlibby LogSnag