add a method inside a method in a class that is subclassed in swift

In Swift, a method can be added inside another method in a class that is subclassed by defining a nested method. Nested method is a method that's defined inside another method. Nested methods can access variables and methods that belong to the outer function, making them useful for organizing code that is related to a specific task.

Here's an example of a subclassed class with a nested method:

main.swift
class MyClass {
    func myMethod() {
        // outer method
        print("Outer method")
        
        func nestedMethod() {
            // inner method
            print("Nested method")
        }
        
        // call the nested method
        nestedMethod()
    }
}

class MySubclass: MyClass {
    override func myMethod() {
        // call the parent method
        super.myMethod()

        // add the subclassed method
        func subclassedMethod() {
            // subclassed method
            print("Subclassed method")
        }
        
        // call the subclassed method
        subclassedMethod()
    }
}
633 chars
31 lines

In this example, the MyClass class has an myMethod() method that defines a nested method nestedMethod(). The nestedMethod() method can only be accessed from within the myMethod() method.

The MySubclass class overrides the myMethod() method of MyClass and adds a new subclassed method subclassedMethod() that can also access the nestedMethod() method from the parent class.

Nested methods can also be defined as class methods using the class keyword instead of func. In this case, the nested method can be accessed both from within the class and from outside the class:

main.swift
class MyClass {
    class func myClassMethod() {
        // outer method
        print("Class method")
        
        class func nestedMethod() {
            // inner method
            print("Nested method")
        }
        
        // call the nested method
        nestedMethod()
    }
}

// call the class method and the nested method
MyClass.myClassMethod()
367 chars
18 lines

gistlibby LogSnag