<html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"></head><body dir="auto"><div>+1<br><br>Sent from my iPhone</div><div><br>On Jun 12, 2016, at 08:01, Антон Жилин via swift-evolution <<a href="mailto:swift-evolution@swift.org">swift-evolution@swift.org</a>> wrote:<br><br></div><blockquote type="cite"><div><div dir="ltr">I've prepared a proper draft:<div><br><div><div><a href="https://github.com/Anton3/swift-evolution/blob/generic-protocols/proposals/NNNN-generic-protocols.md">https://github.com/Anton3/swift-evolution/blob/generic-protocols/proposals/NNNN-generic-protocols.md</a><br></div></div></div><div><br></div><div>- Anton</div></div><div class="gmail_extra"><br><div class="gmail_quote">2016-06-10 17:18 GMT+03:00 Brent Royal-Gordon <span dir="ltr"><<a href="mailto:brent@architechies.com" target="_blank">brent@architechies.com</a>></span>:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex"><span class="">> FWIW they're marked as 'unlikely' here: <a href="https://github.com/apple/swift/blob/master/docs/GenericsManifesto.md#generic-protocols" rel="noreferrer" target="_blank">https://github.com/apple/swift/blob/master/docs/GenericsManifesto.md#generic-protocols</a><br>
><br>
> It would probably be useful to have counterarguments against the points raised in that document if you want to prepare a proposal.<br>
<br>
</span>Here's my counterargument.<br>
<br>
* * *<br>
<br>
Firstly, I think they're underestimating the feature's utility. Generic protocols (real generic protocols, not Sequence<Element>) are already needed to make several existing or likely future features work better. For instance:<br>
<br>
* Pattern matching<br>
<br>
Currently, if you want to customize your type's behavior in a `switch` statement, you do it in an ad hoc, almost Objective-C-like way: You define a free `~=` operator and the compiler resolves the overloads to magically find and use it. There is no way to constrain a generic parameter to "only types that can pattern match against type X", which seems like a pretty useful thing to offer. For instance, in the past people have suggested some sort of expression-based switch alternative. The lack of a pattern matching protocol makes this impossible to implement in either the standard library or your own code.<br>
<br>
If we had generic protocols, we could define a protocol for this matching operator and fix the issue:<br>
<br>
protocol Matchable<MatchingValue> {<br>
func ~= (pattern: Self, value: MatchingValue) -> Bool<br>
}<br>
<br>
protocol Equatable: Matchable<Self> {<br>
func == (lhs: Self, rhs: Self) -> Bool<br>
}<br>
func ~= <T: Equatable>(lhs: T, rhs: T) -> Bool {<br>
return lhs == rhs<br>
}<br>
<br>
extension Range: Equatable, Matchable<Bound> {}<br>
func ~= <Bound: Comparable>(pattern: Range<Bound>, value: Bound) -> Bool {<br>
return pattern.lowerBound <= value && value < pattern.upperBound<br>
}<br>
<br>
Then you could write, for instance, a PatternDictionary which took patterns instead of keys and, when subscripted, matched the key against each pattern until it found a matching one, then returned the corresponding value.<br>
<br>
* String interpolation<br>
<br>
Currently, StringInterpolationConvertible only offers an `init<T>(stringInterpolationSegment: T)` initializer. That means you absolutely *must* permit any type to be interpolated into your type's string literals. This blocks certain important use cases, like a `LocalizedString` type which requires all strings it interacts with to pass through a localization API, from being statically checked. It also would normally require any type-specific behavior to be performed through runtime tests, but just as in `~=`, the Swift compiler applies compile-time magic to escape this restriction—you can write an `init(stringInterpolationSegment:)` with a concrete type, and that will be preferred over the generic one.<br>
<br>
In theory, it should be possible in current Swift to redefine StringInterpolationConvertible to allow you to restrict the interpolatable values by doing something like this:<br>
<br>
protocol StringInterpolationConvertible {<br>
associatedtype Interpolatable = Any<br>
init(stringInterpolation: Self...)<br>
init(stringInterpolationSegment expr: Interpolatable)<br>
}<br>
<br>
(This is no longer generic because I believe Interpolatable would have to be somehow constrained to only protocol types to make that work. But you get the idea.)<br>
<br>
However, in many uses, developers will want to support interpolation of many custom types which do not share a common supertype. For instance, LocalizedString might want to support interpolation of any LocalizedString, Date, Integer, or FloatingPoint number. However, since Integer and FloatingPoint are protocols, you cannot use an extension to make them retroactively conform to a common protocol with LocalizedString.<br>
<br>
With generic protocols, we could define StringInterpolationConvertible like this:<br>
<br>
protocol StringInterpolationConvertible<Interpolatable> {<br>
init(stringInterpolation: Self...)<br>
init(stringInterpolationSegment expr: Interpolatable)<br>
}<br>
<br>
And then say:<br>
<br>
extension LocalizedString: StringInterpolationConvertible<LocalizedString>, StringInterpolationConvertible<Integer>, StringInterpolationConvertible<FloatingPoint> {<br>
init(stringInterpolationSegment expr: LocalizedString) {<br>
self.init()<br>
self.components = expr.components<br>
}<br>
init(stringInterpolationSegment expr: Integer) {<br>
self.init()<br>
self.components.append(.integer(expr))<br>
}<br>
init(stringInterpolationSegment expr: FloatingPoint) {<br>
self.components.append(.floatingPoint(expr))<br>
}<br>
init(stringInterpolation strings: LocalizedString...) {<br>
self.init()<br>
self.components = strings.map { $0.components }.reduce([], combine: +)<br>
}<br>
}<br>
<br>
This example shows an interesting wrinkle: A generic protocol may have requirements which don't use any of the generic types, so that each of the multiple conformances will require members with identical signatures. When this happens, Swift must only allow the member to be implemented once, with that implementation being shared among all conformances.<br>
<br>
* Subtype-supertype relationships<br>
<br>
Though not currently implemented, there are long-term plans to permit at least value types to form subtype-supertype relationships with each other. A protocol would be a sensible way to express this behavior:<br>
<br>
protocol Upcastable {<br>
associatedtype Supertype<br>
<br>
init?(attemptingCastFrom value: Supertype)<br>
func casting() -> Supertype<br>
}<br>
<br>
However, this would require a type to have only one supertype, which isn't necessarily appropriate. For instance, we might want a UInt8 to be a subtype of both Int16 and UInt16. For that to work, Upcastable would have to be generic:<br>
<br>
protocol Upcastable<Supertype> {<br>
init?(attemptingCastFrom value: Supertype)<br>
func casting() -> Supertype<br>
}<br>
<br>
extension UInt8: Upcastable<Int16>, Upcastable<UInt16> { … }<br>
<br>
Without generic protocols, the only way to offer sufficiently flexible subtyping is to offer it as a one-off, ad-hoc feature with special syntax.<br>
<br>
* * *<br>
<br>
Secondly, I think the concerns about people trying to use Sequence as a generic protocol aren't that big a deal. To put it simply: Sequence is *not* a generic protocol. The Swift team controls the definition of Sequence, and we define it to not be generic. If people complain, we explain that generic protocols don't actually do the right thing for this and that they should use existentials instead. We put it in a FAQ. It's just not that big a deal.<br>
<br>
The real concern is not that people will try to use Sequence as a generic protocol, but that they will try to inappropriately make their own protocols generic. I see this as a more minor issue, but if we're worried about it, we can address it by changing the mental model to one which doesn't make it look like a generics feature.<br>
<br>
Basically, rather than thinking of this feature as "generic protocols", it could instead be thought of as "associated type overloading": a particular associated type can be overloaded, and you can use a `where` clause to select a particular overload. This would have a different syntax but handle the same use cases.<br>
<br>
For instance, rather than saying this:<br>
<br>
protocol Matchable<MatchingValue> {<br>
func ~= (pattern: Self, value: MatchingValue) -> Bool<br>
}<br>
<br>
protocol Equatable: Matchable<Self> {<br>
func == (lhs: Self, rhs: Self) -> Bool<br>
}<br>
func ~= <T: Equatable>(lhs: T, rhs: T) -> Bool {<br>
return lhs == rhs<br>
}<br>
<br>
extension Range: Equatable, Matchable<Bound> {}<br>
func ~= <Bound: Comparable>(pattern: Range<Bound>, value: Bound) -> Bool {<br>
return pattern.lowerBound <= value && value < pattern.upperBound<br>
}<br>
<br>
struct PatternDictionary<Matching, Value>: DictionaryLiteralConvertible {<br>
typealias Key = Matchable<Matching><br>
typealias Value = OutValue<br>
<br>
var patterns: DictionaryLiteral<Key, Value><br>
init(dictionaryLiteral pairs: (Key, Value)...) { patterns = DictionaryLiteral(pairs) }<br>
<br>
subscript(matchingValue: Matching) -> Value? {<br>
for (pattern, value) in patterns {<br>
if pattern ~= matchingValue {<br>
return value<br>
}<br>
}<br>
return nil<br>
}<br>
}<br>
<br>
You could instead say:<br>
<br>
protocol Matchable {<br>
@overloadable associatedtype MatchingValue<br>
func ~= (pattern: Self, value: MatchingValue) -> Bool<br>
}<br>
<br>
protocol Equatable: Matchable where MatchingValue |= Self {<br>
func == (lhs: Self, rhs: Self) -> Bool<br>
}<br>
func ~= <T: Equatable>(lhs: T, rhs: T) -> Bool {<br>
return lhs == rhs<br>
}<br>
<br>
extension Range: Equatable, Matchable {<br>
typealias MatchingValue |= Bound<br>
}<br>
func ~= <Bound: Comparable>(pattern: Range<Bound>, value: Bound) -> Bool {<br>
return pattern.lowerBound <= value && value < pattern.upperBound<br>
}<br>
<br>
struct PatternDictionary<Matching, Value>: DictionaryLiteralConvertible {<br>
typealias Key = Any<Matchable where .MatchingValue & Matching><br>
typealias Value = Value<br>
<br>
var patterns: DictionaryLiteral<Key, Value><br>
init(dictionaryLiteral pairs: (Key, Value)...) { patterns = DictionaryLiteral(pairs) }<br>
<br>
subscript(matchingValue: Matching) -> Value? {<br>
for (pattern, value) in patterns {<br>
if pattern ~= matchingValue {<br>
return value<br>
}<br>
}<br>
return nil<br>
}<br>
}<br>
<br>
(Is `MatchingValue |= Bound` a union type feature? I'm not sure. It does have the syntax of one, but there's a separate overload for each type, so I don't think it really acts like one.)<br>
<br>
This is very nearly the same feature, but presented with different syntax—effectively with a different metaphor. That should prevent it from being abused the way the core team fears it will be.<br>
<br>
(One difference is that this version permits "vacuous" conformances: in theory, there's no reason you couldn't conform to a protocol with an `@overloadable associatedtype` and define zero types. On the other hand, that's not necessarily *wrong*, and might even be useful in some cases.)<br>
<span class="HOEnZb"><font color="#888888"><br>
--<br>
Brent Royal-Gordon<br>
Architechies<br>
<br>
</font></span></blockquote></div><br></div>
</div></blockquote><blockquote type="cite"><div><span>_______________________________________________</span><br><span>swift-evolution mailing list</span><br><span><a href="mailto:swift-evolution@swift.org">swift-evolution@swift.org</a></span><br><span><a href="https://lists.swift.org/mailman/listinfo/swift-evolution">https://lists.swift.org/mailman/listinfo/swift-evolution</a></span><br></div></blockquote></body></html>