[swift-evolution] [Swift 4.0] Conditional conformances via protocol extensions

Douglas Gregor dgregor at apple.com
Mon Sep 12 12:04:09 CDT 2016


> On Sep 12, 2016, at 8:14 AM, Paul Cantrell <cantrell at pobox.com> wrote:
> 
> 
>> On Aug 11, 2016, at 9:39 PM, Douglas Gregor via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
>> 
>> FWIW, I'm planning to write a complete proposal for conditional conformances and will start posting drafts once it is far enough along to be useful.
> 
> I’m looking forward to that!
> 
> I’ll throw a potential use case for this your way, both one of the most obvious and one of the nastiest I’ve encountered, in case it helps refine the proposal and/or clarify its limits:
> 
>     // No more runtime exceptions from things buried in
>     // dictionaries! Wouldn’t it be nice?
> 
>     protocol JSONRepresentable { }
> 
>     // So far so good:
> 
>     extension String: JSONRepresentable { }
> 
>     // Hmm, extending protocols is out:
> 
>     extension Integer: JSONRepresentable { }
>     extension FloatingPoint: JSONRepresentable { }
> 
>     // I can imagine a universe where this works:
> 
>     extension Optional: JSONRepresentable
>         where Wrapped: JSONRepresentable { }

Fine so far.

> 
>     // ...but this, oh dear:
> 
>     extension Optional.None: JSONRepresentable { }

This will be ill-formed; Optional.None isn’t a type, it’s part of the value, and allowing the conformance to be present or absent based on a run-time value is a massive complication:


  func f<T: JSONRepresentable>(_: T) { }
  func g(stringOpt: String?)  { f(stringOpt) } // whether the conformance applies or not depends on the run-time value!


> 
>     // Collection would be better but ... extending protocols again:
> 
>     extension Array: JSONRepresentable
>         where Element: JSONRepresentable { }
> 
>     extension Dictionary: JSONRepresentable
>         where Key == String, Value: JSONRepresentable { }
> 
> I imagine this is all a bridge too far for a proposal at this time — and maybe a bridge too far for any conditional protocol conformance ever — but it seems like it needs addressing.

These last two should be fine.

>> It won't have support for protocols conforming to other protocols, though. 
> 
> Curious. Why not? (I’ll happily wait for the proposal if you explain it there.)

The generics manifesto has a sketch of the reason; I will elaborate in the proposal.

	- Doug


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


More information about the swift-evolution mailing list