Swift: The rules of being final (Xcode 6 GM)



The final modifier is used to prevent the subclassing of a class. It is also used to prevent the overriding of properties, methods and subscripts within subclasses of a class that isn't itself final. The keyword is exclusively available to classes, because structs and enums can only inherit from protocols. And although protocols can adopt other protocols, they do not have the capacity to override the protocol that they adopt.

The rules of being final

  1. final can be used to prefix a class declaration in order to prevent subclassing
  2. final can be used within a (non-final) class to prefix a method, property or subscript
  3. final cannot be used with structs or enums
  4. final can prefix type methods and properties, as well as instance methods and properties

Code examples

The following code fails to compile, because the Father class is final and cannot be subclassed.
final class Father {   
    // code goes here
}

class Grandfather:Father {
    // code goes here
}
Removing the final keyword it would work, but in this next example the subclassing works
class Father {
    
    final class func tryThis() {
        // code goes here
    }
}

class Grandfather:Father {

    override class func tryThis() {
        // code goes here
    }
}
while the override of tryThis() fails because it was made final.

Endorse on Coderwall

Comments