Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - class method which must be overridden by subclass

Is there a standard way to make a "pure virtual function" in Swift, ie. one that must be overridden by every subclass, and which, if it is not, causes a compile time error?

like image 327
JuJoDi Avatar asked Jun 08 '14 22:06

JuJoDi


People also ask

Which methods must be overridden in the subclass?

Subclass must override methods that are declared abstract in the superclass, or the subclass itself must be abstract. Writing Abstract Classes and Methods discusses abstract classes and methods in detail.

Can we override class method in Swift?

In Swift Inheritance, the subclass inherits the methods and properties of the superclass. This allows subclasses to directly access the superclass members. Now, if the same method is defined in both the superclass and the subclass, then the method of the subclass class overrides the method of the superclass.

When should you override a method in a subclass?

When a method in a subclass has the same name, same parameters or signature, and same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class.

Which methods are not allowed to override in subclass?

3) An instance method cannot override a static method, and a static method cannot hide an instance method.


2 Answers

You have two options:

1. Use a Protocol

Define the superclass as a Protocol instead of a Class

Pro: Compile time check for if each "subclass" (not an actual subclass) implements the required method(s)

Con: The "superclass" (protocol) cannot implement methods or properties

2. Assert in the super version of the method

Example:

class SuperClass {     func someFunc() {         fatalError("Must Override")     } }  class Subclass : SuperClass {     override func someFunc() {     } } 

Pro: Can implement methods and properties in superclass

Con: No compile time check

like image 104
drewag Avatar answered Oct 13 '22 15:10

drewag


The following allows to inherit from a class and also to have the protocol's compile time check :)

protocol ViewControllerProtocol {     func setupViews()     func setupConstraints() }  typealias ViewController = ViewControllerClass & ViewControllerProtocol  class ViewControllerClass : UIViewController {      override func viewDidLoad() {         self.setup()     }      func setup() {         guard let controller = self as? ViewController else {             return         }          controller.setupViews()         controller.setupConstraints()     }      //.... and implement methods related to UIViewController at will  }  class SubClass : ViewController {      //-- in case these aren't here... an error will be presented     func setupViews() { ... }     func setupConstraints() { ... }  } 
like image 42
JMiguel Avatar answered Oct 13 '22 15:10

JMiguel