Abstract functions in Swift Language
I'd like to create an abstract function in swift language. Is it possible?
class BaseClass {
func abstractFunction() {
// How do I force this function to be overridden?
}
}
class SubClass : BaseClass {
override func abstractFunction() {
// Override
}
}
There no concept of abstract in Swift (like Objective-C) but you can do this :
class BaseClass {
func abstractFunction() {
preconditionFailure("This method must be overridden")
}
}
class SubClass : BaseClass {
override func abstractFunction() {
// Override
}
}
What you want is not a base class, but a protocol.
protocol MyProtocol {
func abstractFunction()
}
class MyClass : MyProtocol {
func abstractFunction() {
}
}
If you don't supply abstractFunction in your class it's an error.
If you still need the baseclass for other behaviour, you can do this:
class MyClass : BaseClass, MyProtocol {
func abstractFunction() {
}
}