[swift-evolution] [swift-evolution-announce] [Returned for revision] SE-0117: Default classes to be non-subclassable publicly
karoly at lorentey.hu
Sat Jul 16 18:05:06 CDT 2016
> On 2016. Jul 16., at 16:45, Karl via swift-evolution <swift-evolution at swift.org> wrote:
> Sorry to mail 3 times in a row, but as I finished I remembered a concrete example of where sealed protocols would be helpful:
> UIKit has a UITextInput protocol, which is used by custom text object which want to interact with the keyboard. It has a delegate property, of type UITextInputDelegate (another protocol).
> I have seen lots of people try to have their own objects conform to UITextInputDelegate and set themselves as the delegate on a UITextInput object. That is the wrong usage of the property. You are never supposed to conform to UITextInputDelegate; the system has something which conforms to it, and it will set itself as your delegate at some point during text input. You use it to notify the system about changes to the text content and selection region.
> If it was a sealed protocol, the UIKit API authors would be able to more clearly communicate this intention and people wouldn’t be able to fall in this trap. The only other way they could do it would be to use a concrete final type, which evidently they didn’t want to do (possibly because it has internal subclasses and can’t be final).
I think there is at least one legitimate case where you'd still want to implement these kinds of protocols: when you're writing unit tests and you want to create a mock delegate to verify that your code calls the delegate methods correctly.
Also, interface inheritance is much less dangerous than implementation inheritance; I can't think of a case where allowing external code to implement a protocol could lead to maintenance problems for the framework author like subclassing does. (Although I agree the user confusion that you described occurs a lot.)
More information about the swift-evolution