[swift-evolution] [Pre-proposal] Use of angle bracket type generics with protocols

Haravikk swift-evolution at haravikk.me
Fri Feb 26 05:22:28 CST 2016

One of the big things that bugs me about working with protocols and generics is that they have a fundamentally different style to working with generics on structs and classes. While has some minor benefits on differentiating them, I think that overall it results in inconsistency that makes them harder to work with.

I’d like to propose two fairly minor changes that allow protocols to be defined using angle brackets for generics to make things much easier. 

First is allowing a protocol to be defined using angle brackets for its generic type(s) like so:

	protocol FooType<Element, Index:ForwardIndexType> {
		func getElement(atIndex:Index) -> Element?

In this example the protocol Foo has implicit type aliases for Element and Index, which can be fulfilled like so:

	struct Foo<Element> : FooType<Element, Int> {
		func getElement(atIndex:Index) -> Element? { … }

The other important case is defining type constraints with protocol generics, currently we have to do stuff like this:

	func append<S:SequenceType where S.Generator.Element == Element>(contentsOf theSequence:S) { … }

However, while definition with a where clause is powerful, in the majority of cases it’s much more complex than it needs to be. So I’d like to propose that we can have the following:

	protocol SequenceType<Element> { … }
	func append(contentsOf theSequence:SequenceType<Element>) { … }

Behind the scenes these may be unwrapped into type aliases and where clauses like we have now, but for the developers this is much, much simpler to work with, especially when most generic constraints are pretty simple.

I’m not proposing the removal of where clauses as they can be really useful in more unusual cases, so will still have utility there. I’m not so sure about explicit type alias declaration like we have now though; using the angle brackets to declare these seems just as capable to me unless there are some cases I haven’t considered.

This seems like something that may have been discussed in the past, but I’m not that great on specific terminology for features (I’m not as well versed as others are on the correct names for language features) so I haven’t found anything, but fully expect that I may have missed it somehow, in which case a link would be appreciated.

But if no proposal currently exists then I’d love to know, as I could try to create a more formal proposal for this if necessary, as I know that I for one would benefit greatly from simplified protocol generics, as they’re currently one of my least favourite features to use syntactically, but one I need to use a lot.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160226/6fac3fa2/attachment.html>

More information about the swift-evolution mailing list