[swift-evolution] Overriding specific methods when adopting protocols with extension

Iman Zarrabian iman at omts.fr
Thu Mar 23 10:15:16 CDT 2017


Hi,  
This is my first contribution to this list so I’m a little nervous. 
I’ve been refactoring some code in one of our internal frameworks and noticed something I didn’t noticed about protocols before. 
Maybe I’m missing the big picture here but I’ll expose the issue to you anyway.
Consider these protocols and classes declarations :

protocol Foo {
    func bar()
    func specificBar()
    func moreBar()
}

extension Foo {
    func specificBar() {
        print("default specificBar implementation")
    }
}

extension UIView: Foo {
    func bar() {
        print("uiview default bar")
        specificBar()
        moreBar()
    }
    
    func moreBar() {
        print("UIView is foo compliant and implements moreBar function")
    }
}

class CustomView: UIView {
    func startJob() {
        bar()
    }
    
    func specificBar() {
        print("CustomView specific bar implementation")  //This is the implementation I want for specificBar but this is not the one picked at runtime.
    }
}


let view = CustomView()
view.startJob()

//Prints :
//uiview default bar
//default specificBar implementation
//UIView is foo compliant and implements moreBar function

I was wondering if it is a good idea to give the CustomView class the power to be more specific about it’s parent protocol adoption.

It seems to me that implementation of a protocol method cannot be easily changed by subclasses of the class that actually adopts the protocol in the first place. IMO one way to achieve the kind of specialization I’m trying to do is to create two protocols and another would be to implement a version of specificBar in the superclass (UIView here)

But does it make sense to consider some kind of cherry picking (with a new keyword) for those methods we want to implement more precisely than the one provided on the protocol extension?
Consider this new code for CustomView : 

class CustomView: UIView {
    func startJob() {
        bar()
    }
    
    override adoption func specificBar() {  //or override protocol => implements a method from a protocol adopted by the superclass
        print("CustomView specificBar implementation")
    }
}

let view = CustomView()
view.startJob()

//Would print :
//uiview default bar
//CustomView specificBar implementation
//UIView is foo compliant and implements moreBar function

I would appreciate your feedback.

--
Iman Zarrabian
@imanzarrabian
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170323/75f6ebbe/attachment.html>


More information about the swift-evolution mailing list