0

Assume the below playground:

protocol MyProtocol
{
    func MyFunc()
}

class MyBase : MyProtocol
{
    func MyFunc()
    {

    }
}

class MyClass : MyBase, MyProtocol
{

}

I was expecting this to not compile, and nag about not implementing my protocol. But unlike other languages, Swift seems to think its fine if the protocol conforms to the base class.

How can I get MyClass to force my method to be overridden?

I'm using Swift 1.1, tia.

ericosg
  • 4,926
  • 4
  • 37
  • 59
  • It's implemented, it's just very boring: `{}`. – Andrew Jaffe Apr 09 '15 at 13:19
  • Use composition rather than inheritance, this situation is legal in C#, Java, Objective-C and C++ as well AFAIK – Mgetz Apr 09 '15 at 13:20
  • @Mgetz, yes definitely valid in other languages. Not sure about using composition though since he is not trying to get any functionality out of the super class in this example. But you are very likely correct, just hard since we do not have much context about what he is actually doing. I think this could be an [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – Firo Apr 09 '15 at 13:26
  • 1
    Note that in Swift, this generally hints you should be using a struct rather than a class. If you don't want to inherit the empty functionality, avoid inheritance. Swift generally uses protocols as its abstract types. – Rob Napier Apr 09 '15 at 13:29
  • 1
    @Firo I come from C++ where I might have the `p_impl` implement protocols (interfaces) that I don't have the exposed class implement and vice versa. So to me composition would seem the logical work around here. But I agree that this seems XY. – Mgetz Apr 09 '15 at 13:38

1 Answers1

5

Your code is definitely valid. MyClass inherits from MyBase which already conforms to MyProtocol, so having the subclass also conform to it is completely redundant. That being said, you are basically looking for an abstract function which does not really exist in Swift, the closest I think you can get to achieving what you want is recommended in this answer. So in your base class just give a warning if not overriden:

class MyBase : MyProtocol {
    func MyFunc() {
        fatalError("This method must be overridden") 
    }
}

As recommended in the question comments, a different approach may work better for what you are attempting to do (e.g. composition or using a struct), but it is a bit hard to recommend a different solution without knowing more about what you are trying to achieve (rather than just the expected solution). If you do provide additional details you may receive a more suitable answer.

Community
  • 1
  • 1
Firo
  • 15,448
  • 3
  • 54
  • 74
  • 1
    indeed i think i was looking for a virtual method and abstract classes and got confused when i saw a protocol, which indeed is similar to an interface in other languages. – ericosg Apr 09 '15 at 13:47