Swift - class method which must be overridden by subclass

前端 未结 6 1153
余生分开走
余生分开走 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:39

    Being new to iOS development, I'm not entirely sure when this was implemented, but one way to get the best of both worlds is to implement an extension for a protocol:

    protocol ThingsToDo {
        func doThingOne()
    }
    
    extension ThingsToDo {
        func doThingTwo() { /* Define code here */}
    }
    
    class Person: ThingsToDo {
        func doThingOne() {
            // Already defined in extension
            doThingTwo()
            // Rest of code
        }
    }
    

    The extension is what allows you to have the default value for a function while the function in the regular protocol still provides a compile time error if not defined

提交回复
热议问题