Swift - class method which must be overridden by subclass

前端 未结 6 1163
余生分开走
余生分开走 2020-12-02 10:31

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 c

6条回答
  •  忘掉有多难
    2020-12-02 10:49

    You can use protocol vs assertion as suggested in answer here by drewag. However, example for the protocol is missing. I am covering here,

    Protocol

    protocol SomeProtocol {
        func someMethod()
    }
    
    class SomeClass: SomeProtocol {
        func someMethod() {}
    }
    

    Now every subclasses are required to implement the protocol which is checked in compile time. If SomeClass doesn't implement someMethod, you'll get this compile time error:

    error: type 'SomeClass' does not conform to protocol 'SomeProtocol'

    Note: this only works for the topmost class that implements the protocol. Any subclasses can blithely ignore the protocol requirements. – as commented by memmons

    Assertion

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

    However, assertion will work only in runtime.

提交回复
热议问题