Reputation: 2241
I was wondering if there's a way to enforce protocol's on subclassing particular classes?
an example is:
protocol MYWindowControllerProtocol {
var identifier: String { get }
}
then later in I create a subclass of NSWindowController in order to inherit the needs I've laid out above:
class MYWindowController: NSWindowController, MYWindowControllerProtocol{
}
The problem I have is that it requires the subclass to inherit the protocol needs (which makes sense)... Is there a way about this so that only subclasses of "MYWindowController" actually have to inherit the needs? Without my base MYWIndowController
class being forced to?
What I'm trying to achieve is:
1) Ensuring that anything subclassed from MYWindowController
is required to implement various functions or vars per the protocol
2) Tha the actual class MYWindowController (the parent MYWindowCOntroller
) isn't forced to, as it's merely an abstract class
Cheers,
A
Upvotes: 1
Views: 45
Reputation: 11123
You cannot do this at compile time in Swift (there are languages that have the concept of an abstract
class, like Java, which you can do this with at compile time). Your only option is a run-time solution. In your base class, you can provide implementations that call fatalError(String) and pass a message like "Subclass must provide implementation of method/variable <#signature#>". This will cause the app to fail at runtime if no implementation is provided, so it is a little risky if it isn't absolutely going to happen (i.e., could be overlooked in testing).
var identifier: String {
get {
fatalError("Subclass must provide implementation for var identifier")
}
}
Note: I would suggest that you could use Swift 2's protocol extensions to accomplish the same thing, but there appears to be a bug with method dispatch when you have a class that conforms to a protocol and provides no implementation, the subclass implementation is not dispatched correctly.
Upvotes: 1