[swift-evolution] [Proposal] Associated Type and Generic One-to-One Mapping

Víctor Pimentel vpimentel at tuenti.com
Sat Jun 24 14:21:26 CDT 2017


> On 24 Jun 2017, at 08:50, David Sweeris via swift-evolution <swift-evolution at swift.org> wrote:
> 
> 
>> On Jun 23, 2017, at 5:28 PM, David Moore via swift-evolution <swift-evolution at swift.org> wrote:
>> 
>> I do indeed have quite a few real examples of this, such prompted me to bring this up. I think this could be done without any impact to existing code, but it would require some type of keyword. Take the following as a possible prototype.
>> 
>> protocol Foo { 
>>    associatedtype T
>> }
>> 
>> struct Bar<T> : Foo {
>>    keyword typealias T // Or really any other syntactical implementation.
>> }
>> 
>> With an opt-in method we could implement this without affecting existing code, thereby making this more viable. I will send some examples later.
> 
> At one point there was talk of just having generic parameters automatically becoming typealiases:
> struct Bar<T> : Foo {
>    // `T` is automatically an implicit typealias for, well, `T`
> }
> 
> Dunno if that’s still the plan (or to what degree it ever was), but it’d work for me. I don’t even think it’d break source compatibility (though it may make a lot of typealiases unneeded.
> 
> - Dave Sweeris

Automatic implicit type aliases sounds the ideal solution, at least from the point of view of the programmer.

If that is too difficult or costly to the compiler, I don't think adding another keyword would be a good solution or compromise. Maybe it can be also be solved by supporting some way of referring to Bar.T and Foo.T explicitly:

struct Bar<T> : Foo {
   typealias T = Bar.T
}

Or:

struct Bar<T> : Foo {
   typealias Foo.T = Bar.T
}

Or:

struct Bar<T> : Foo {
   typealias Foo.T = T
}

The compiler could help by suggesting fix-it if encountered with the original non-compiling code.

--
Víctor Pimentel


More information about the swift-evolution mailing list