Sobes.tech
Junior — Middle

What does the use of the keyword final in a class declaration signify in the context of dispatching type?

sobes.tech AI

Answer from AI

In Swift, the keyword final when declaring a class means that this class cannot be inherited. It affects the method dispatch type: the compiler can use static (or direct) dispatch instead of dynamic, since it is guaranteed that methods will not be overridden in subclasses.

This improves the performance of method calls, as there is no need to look up the method implementation at runtime — the call is made directly.

Example:

final class MyClass {
    func greet() {
        print("Hello")
    }
}

// Cannot create a subclass of MyClass
// class SubClass: MyClass {} // Compilation error

Thus, final helps the compiler optimize method calls by using static dispatch instead of dynamic.