[swift-evolution] Protocol requirement `where` clauses constraining associated types
brent at architechies.com
Wed Feb 8 23:57:56 CST 2017
In an article on `Collection` today*, Ole Begemann points out that `index(of:)`, along with other `Equatable`- and `Comparable`-constrained `Collection` methods, cannot be overridden. Actually, it *can* be, but only through a private mechanism—there's a `_customIndexOfEquatableElement(_:)` method that's invisible in the generated interface. But that only proves the need for a way to make methods like these overridable.
The problem is that the `index(of:)` method should only be offered when the element is `Equatable`—otherwise it simply won't work. But there's no way to specify this rule in current Swift. In theory, we could describe such a requirement with something like this:
func index(of element: Iterator.Element) -> Index? where Iterator.Element: Equatable
But this is not permitted—you get an error indicating that `where` clauses are only allowed on generic methods. Adding a spurious generic parameter allows this code to compile, but with a deprecation warning indicating that this is deprecated. I don't know if it would actually behave correctly, however.
Is this a feature we should add? Is this the way to add it? Would it have non-additive ABI impact? (The private `index(of:)` override would certainly go away, but that's why it's private, I suppose.) I don't seem to remember seeing something like this in the generics manifesto, so I thought it was worth bringing up.
More information about the swift-evolution