Swift - class method which must be overridden by subclass

前端 未结 6 1162
余生分开走
余生分开走 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 11:04

    There isn't any support for abstract class/ virtual functions, but you could probably use a protocol for most cases:

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

    If SomeClass doesn't implement someMethod, you'll get this compile time error:

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

提交回复
热议问题