[swift-evolution] [swift-evolution-announce] [Returned for revision] SE-0117: Default classes to be non-subclassable publicly
razielim at gmail.com
Sat Jul 16 09:45:32 CDT 2016
> On 16 Jul 2016, at 16:32, Karl <raziel.im+swift-users at gmail.com> wrote:
>> On 16 Jul 2016, at 16:10, T.J. Usiyan via swift-evolution <swift-evolution at swift.org> wrote:
>> What happens if I want an `internal` subclass of an `open` class?
> That should be allowable. You may want some optimised implementations, similar to how Apple used class-clusters in Obj-C. I don’t think that same pattern is exactly possible in Swift (I don’t think a class can set ‘self’ in its initialiser, or at least it couldn’t in Swift 1). But the same principle applies - you may want a public class which you don’t allow others to subclass, but you might have a static method or other function which returns an internal optimised implementation.
> If you used a protocol rather than a concrete type in that case, theoretically others could conform to it and throw their own objects back at your code, which goes against the point of this proposal.
> We might think about creating ‘sealed’ protocols, too.
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).
More information about the swift-evolution