3

I have below hierarchical inheritance relationship in Swift,

class Base {

    func method1() { }
    func method2() { }
}

class Child: Base {

    override func method1() { }
    func method3() { }
}

class GrandChild: Child {

}

Now, I want to enforce GrandChild to override method1() from Base class and method3() from Child class. How can I do so? Any workaround or better approach?

Sazzad Hissain Khan
  • 37,929
  • 33
  • 189
  • 256
  • @LalKrishna that does not answer my question. My intention is not just for making class abstract rather propagating restriction in `base->child->grandchild` flow. – Sazzad Hissain Khan Feb 10 '20 at 06:19
  • This is not currently supported by Swift. – Rohan Bhale Feb 10 '20 at 06:32
  • 1
    You can’t even enforce a child class to override a method since swift doesn’t have abstract classes. It’s hard to suggest a solution without knowing the use case for this but the general advice in swift for this is to use a protocol. – Joakim Danielson Feb 10 '20 at 07:27

1 Answers1

2

There is no way to do it on the compile time in Swift. The feature of enforcing method override is not present in Swift.

But there is a work around.

You can do that by putting a fatal error fatalError("Must Override").

Consider the following example.

class Base {
    func method1() {
      fatalError("Must Override")
    }
    func method2() { }
}

class Child: Base {
    override func method1() { }
    func method3() {
      fatalError("Must Override")
    }
}

class GrandChild: Child {
   func method1() { }
   func method3() { }
}

But the above method will not give any compile time errors. For that there is another workaround.

You can create a protocol.

protocol ViewControllerProtocol {
   func method1()
   func method3()
}

typealias ViewController = UIViewController & ViewControllerProtocol

So if you implement this protocol and do not implement the methods compiler will generate an error.

As a feature of protocols in Swift you can also provide a default implementation of the methods in a protocol extension.

Hope this helps.

nishith Singh
  • 2,968
  • 1
  • 15
  • 25