Centurion
Centurion

Reputation: 14304

Can a method be overridden by protocol default implementation?

As of Swift 2, it became possible to provide our own method implementation (protocol default implementation) in protocols for the classes that will implement these protocols. But can we override existing methods?

To me protocols in Swift 2 look like a mix of protocols + categories. While in general it's good and starts to promote composition based programming over inheritance based programming, however I lack the possibility to override existing methods thus have a full control and flexibility and have full composition. This means being able to grab bunch of protocols with default implementations add needed behaviour to my classes (and override if needed). If it's not possible directly, maybe there's a way to workaround this?

UPDATE. The reason why I want to do this is I don't like using UITableViewController and UICollectionViewController. Instead I have my own very top superclass CoreViewController and couple second level base classes (BaseViewController, BaseDetailsViewController and BaseWebViewController) where I contain all common shared code. Yes, this is inheritance and I would like to have a different implementation using composition, therefore I liked Swift 2 approach with the protocols. This way I will be able to use UITableViewController (with static cells) and still attach my common code. However, I need to be able to override couple its methods, for example like alloc. I have quite simple (implementation of this method)[https://github.com/GitTennis/SuccessFramework/blob/master/Templates/BusinessApp/BusinessApp/Core/CoreViewController.m] which smartly auto picks correct view controllers class for my universal apps (all my view controllers have _ipad or _iphone suffix).

Upvotes: 1

Views: 814

Answers (1)

0x416e746f6e
0x416e746f6e

Reputation: 10136

From what I recall from WWDC video, if a class provides an implementation for a method that also has a protocol default implementation, the one from the class wins. I.e. the protocol's implementation is only used when the class does not provide one.

IMO, if that would be other way around (or if there would be another way to override class implementation by a protocol implementation), that would open some nasty doors. E.g. suddenly standard framework functionality working differently because of that.

At any rate, why would you want to override existing class method(s) by protocol default implementation?

Upvotes: 2

Related Questions