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

Paul Cantrell cantrell at pobox.com
Mon Sep 12 13:55:29 CDT 2016


> On Sep 12, 2016, at 12:04 PM, Douglas Gregor <dgregor at apple.com> wrote:
> 
>> On Sep 12, 2016, at 8:14 AM, Paul Cantrell <cantrell at pobox.com <mailto:cantrell at pobox.com>> wrote:
> 
>>     // ...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!

Got it. This is more or less what I meant by “oh dear,” but better spelled out.

Two thoughts pop up from your response:

1. I just realized that my extension Optional.None is totally unnecessary. This covers nil as well as wrapped values:

    extension Optional: JSONRepresentable
        where Wrapped: JSONRepresentable    

…and there’s no need to special-case nil.

I still fall into the trap of forgetting that in Swift, different nils can have different types. I still vaguely think of there being a single-value NilType (wrong) that’s a subtype (wrong) of all reference types (wrong). Old habits die hard!

2. That notwithstanding, I’ve come across a few cases where it would be useful to have individual enum cases either be different subtypes of their enclosing enum type, or conform to different protocols. I’ll post next time I hit a useful example of that situation.

> 
>>> 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.

I await it with patient excitement. :)

Cheers, P


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


More information about the swift-evolution mailing list