The Swift method is a class that must be overridden by a subclass.

Is there a standard way to create a "pure virtual function" in Swift, i.e. one that needs to be overridden by each subclass and which, if it isn't, causes a compile-time error?

+52
abstract swift swift-protocols
Jun 08 '14 at
source share
3 answers

There is no support for abstract classes / virtual functions, but in most cases you could use the protocol:

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

If SomeClass does not implement someMethod, you will get this compile-time error:

 error: type 'SomeClass' does not conform to protocol 'SomeProtocol' 
+32
Jun 08 '14 at 22:15
source share

You have two options:

1. Use protocol

Define a superclass as a protocol instead of a class

Pro : checking compile time if each "subclass" (and not the actual subclass) implements the required method (s)

Con : "Superclass" (protocol) cannot implement methods or properties

2. Approval in the super version of the method

Example:

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

Pro : you can implement methods and properties in a superclass

Con : compile-time checking

+91
Jun 08 '14 at 10:18
source share

Another workaround, if you have too many "virtual" methods, is for the subclass to pass the "implementations" to the base class constructor as function objects:

 class MyVirtual { // 'Implementation' provided by subclass let fooImpl: (() -> String) // Delegates to 'implementation' provided by subclass func foo() -> String { return fooImpl() } init(fooImpl: (() -> String)) { self.fooImpl = fooImpl } } class MyImpl: MyVirtual { // 'Implementation' for super.foo() func myFoo() -> String { return "I am foo" } init() { // pass the 'implementation' to the superclass super.init(myFoo) } } 
+12
Jun 30 '14 at
source share



All Articles