[swift-evolution] [Draft] open and public protocols

Karl Wagner razielim at gmail.com
Sun Feb 19 11:45:29 CST 2017


> On 19 Feb 2017, at 17:36, David Hart <david at hartbit.com> wrote:
> 
> This makes more sense already. But in this case, wouldn't I be interested, as a client, in creating my own TextStreams, some of which might write to a custom log file, to a web service, etc... ?
> 
> On 19 Feb 2017, at 17:00, Karl Wagner <razielim at gmail.com <mailto:razielim at gmail.com>> wrote:
> 
>> 
>>> On 19 Feb 2017, at 16:17, David Hart via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
>>> 
>>> I still don't see the use case for this. Perhaps I'm wrong, but if an API creates a protocol for the sole purpose of representing a set of concrete types, that looks more to me like bad API design, and not a missing feature in the language. Can you give me a small concrete real-world example of an API which requires that? 
>> 
>> 
>> Whether or not a protocol is open is also a part of API expressivity; often a library will want to expose a protocol only as a way to enable generic/existential programming over a fixed set of types, without intending that any clients add new conformers. Protocols are crucial to expressing the shared patterns amongst the set of types.
>> 
>> For example, I might have a TextStream protocol:
>> 
>> public protocol TextStream {
>>     func write(_: String)
>> }
>> 
>> And I might decide to expose a property as type “TextStream” purely because I reserve the right to change the underlying concrete type. I want clients to work on the protocol-existential level.
>> 
>> public class Component {
>>     var debugWriter: TextStream
>> }
>> 
>> By doing that, the underlying concrete type is no longer part of my API or ABI. I can change it between versions without breaking clients, but it’s not meaningful for any clients to create their own TextStreams; that’s not part of what my library does/allows.
>> 
>> - Karl

Perhaps, but there are times when you don’t want that, or when accommodating custom instances is not so straightforward. The debugWriter instance is only _exposed_ as a “TextStream”; but there may be more (internal) requirements on the underlying instance - e.g. that it is Flushable, InitialisableFromNativeFileObject, or whatever. I would rather not expose them all, and just expose the instance as “something which is a TextStream, so you can call TextStream methods on it”, if I decide that’s all they need to know.

- Karl 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170219/aa7f859b/attachment.html>


More information about the swift-evolution mailing list