The role of the final

The final keyword is used to modify variables, methods, and classes that are not inheritable.

If a class wants to inherit from Animal, the compiler will error:

final class Animal {
    let name: String
    init(name: String) {
        self.name = name
    }
    
    func eat() { }
}
Copy the code

Property not inheritable:

class Animal {
    final let name: String
    init(name: String) {
        self.name = name
    }
    
    func eat() { }
}
Copy the code

Method not inheritable:

class Animal {
    let name: String
    init(name: String) {
        self.name = name
    }
    
    final func eat() { }
}
Copy the code

Conclusion: Anything modified with final is not inherited. It can modify properties, methods, and classes.

What is the advantage

Using Final can improve performance. The use of final decoration can avoid Dynamic Dispatch of the system. More optimizations for Dynamic Dispatch can be found here.