I agree that labels for generic parameters would be a nice addition to the language.
One generic type is generally fine (Array<Int>
), two generic types can be okay if you are familiar with the type already (Dictionary<String, Int>
), but three or more generic types start becoming an incomprehensible soup (Foo<String, Int, String>
).
They remind me of C functions: foo(42, -7, true)
. Swift improves on those by adding labels, and it makes just as much sense for generic types as it does for functions IMO.
We can bikeshed the syntax after we agree on the direction, IMO. "<Element: Int>"
has things going for it; I've also suggested that the compiler could just DWIM when users mistakenly constrain to a concrete type. There are other possibilities and considerations, though.
Swift does favour putting API authors in control. If we already had the general constraint syntax, you could imagine allowing API authors to define aliases for common constraints, as they see fit.
This could involve minimal code changes, unlike the highly invasive changes proposed here.
#if swift(>= X)
typealias Collection<T> = Collection<.Element == T>
#endif
// Can totally live alongside the regular Collection protocol.
protocol Collection: Sequence { ... }
But again, I think this is a very separable feature and warrants its own discussion.
I've already outlined the issues as I see them in previous posts in this thread:
- This is an opt-in, highly invasive feature for library developers.
- You don't get any constrained opaque types unless you opt-in and make those very invasive changes.
- This is a more controversial shorthand (IMO), and should be evaluated in isolation.
This proposal includes an entirely new way of declaring protocols, not just using them, while at the same time being very restrictive, not scalable, and going against an important Swift philosophy that we should favour clarity over brevity at the point of use. It's the wrong place to start.
I think the most logical way to approach this is to implement the general feature and syntax (Slava says it's already somewhat implemented behind flags - great!), and discuss this limited shorthand later. Bundling the shorthand together with the slam-dunk, very, very desirable feature of constraints on opaque types, is just poor practice.