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.swift633 chars31 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.swift367 chars18 lines
gistlibby LogSnag