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

David Moore mooredev at me.com
Fri Jun 23 17:03:35 CDT 2017


Hello Swift Evolution,

This may have already been discussed before, but I just came across a bothersome language aspect which reminded me to propose a solution. Currently, if we want to add generics to a protocol the only way to do so is with associated types. I am quite fine with the current approach with respect to those semantics.

There is, however, a weakness that is built in with using associated types. That weakness is the lack of associated type and generic inference. To be more clear about what I mean, take the following as an example.

protocol Foo {
    associatedtype T
}

The foregoing protocol is quite basic, but uses an associated type with the name “T.” Giving the associated type that name will illustrate the dilemma encountered later on down the pipeline.

struct Bar<T> : Foo {
    // What am I supposed to do? The name is used for both the generic and the type alias Foo needs for conformance.
    typealias T = T // Error!
}

The above illustrates a situation where we want to connect the generic, which is supposedly named appropriately, and the protocol’s associated type. There is no elegant solution for this at the moment. All I could do is the following.

struct Bar<U> : Foo {
    typealias T = U // Not nearly as readable.
}

Now, there may be a few ways to go about adding support for generic inference. The compiler as it is already does some awesome inference get when it comes to generics, so why not take it a step further? I propose the introduction of a keyword, or anything else that could work, to specify explicitly what a given type alias declaration would do when it comes to inferencing. Requiring a keyword would ensure source compatibility remains intact, and it would also make the code more readable.

I don’t know if this would be something that people could find useful, but I surely would. The implicit mapping of an associated type and a given generic by their names, would be a natural development.

Let me know if this is just useless, or if could be a potential feature.

Thank you,
David Moore


More information about the swift-evolution mailing list