[swift-evolution] [Pitch] Nested types in protocols (and nesting protocols in types)

Slava Pestov spestov at apple.com
Mon Oct 24 05:25:50 CDT 2016


Hi Karl,

I just saw your draft after sending my first reply earlier; I posted some additional comments on the gist.

Also I remembered that Jordan Rose and I were talking about this recently in the context of the ClangImporter, so I'm CCing him in case he wants to share some thoughts.

> On Oct 21, 2016, at 6:21 PM, Karl via swift-evolution <swift-evolution at swift.org> wrote:
> 
> I had a go at writing this up formally:
> 
> https://gist.github.com/karwa/4c6bff75f8fa84b16df2c8caae97d622 <https://gist.github.com/karwa/4c6bff75f8fa84b16df2c8caae97d622>
> 
> Is there anything I missed?
> 
> - Karl
> 
>> On 17 Oct 2016, at 20:44, Adrian Zubarev <adrian.zubarev at devandartist.com <mailto:adrian.zubarev at devandartist.com>> wrote:
>> 
>> That option should not be disallowed. Here is a simple example you might want to build at some point:
>> 
>> protocol ProtocolName {
>>      
>>     associatedtype AssociatedType
>> }
>> 
>> extension ProtocolName where AssociatedType == Int {
>>   
>>     struct InnerType {}
>> }
>> 
>> 
>> 
>> -- 
>> Adrian Zubarev
>> Sent with Airmail
>> 
>> Am 17. Oktober 2016 um 20:30:58, Karl via swift-evolution (swift-evolution at swift.org <mailto:swift-evolution at swift.org>) schrieb:
>> 
>>> Is your vision that each conforming type would have to provide its own nested type as specified by the protocol?
>>> 
>>> Or could the protocol itself define a nested type and anything could use it?
>>> 
>>> protocol FloatingPoint: … {
>>>     enum RoundingRule {
>>>         // Do I put an implementation here?
>>>     }
>>> }
>>> 
>>> No, types which are defined inside the protocol are implemented there. Providing your own types to satisfy a conformance is what associated types are for.
>>> 
>>> If you wanted something like that, you could do it with a nested protocol + associated type:
>>> 
>>> protocol FloatingPoint {
>>> 
>>>     protocol _RoundingRule { func round(_ : Super) -> Super }
>>>     associatedType RoundingRule : _RoundingRule
>>> }
>>> 
>>> struct Float : FloatingPoint {
>>> 
>>>     enum RoundingRule : _RoundingRule {
>>>         func round(_ val: Float) -> Float {
>>>             /* switch self, perform rounding… */ 
>>>         }
>>>     }
>>> }
>>> 
>>> That brings up an interesting point, though - we would need a way to refer to the outer protocol (I used “Super” here).
>>> 
>> 
>> 
> 
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

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


More information about the swift-evolution mailing list