[swift-evolution] Swift 3 Generics

Douglas Gregor dgregor at apple.com
Thu Dec 17 11:54:22 CST 2015

> On Dec 17, 2015, at 12:37 AM, David Waite <david at alkaline-solutions.com> wrote:
>> On Dec 15, 2015, at 9:45 PM, Douglas Gregor via swift-evolution <swift-evolution at swift.org> wrote:
>> This is something like:
>>  extension CollectionType : Equatable where Generator.Element : Equatable {}
>> This is probably not a priority for Swift 3. It seems very cool, and I've advocated for similar features in the past (in more static generics systems), but the potential for ambiguities with such definitions is very high and the runtime cost for asking questions such as "is this T Equatable?" can be very high when this feature is in play. 
> I’m not sure about the runtime cost of non-“existential" protocols like Equatable, which can’t be casted to at runtime today. Of course, this makes that there are multiple ‘kinds’ of protocols with different usage that are declared in the same way more complex than it is today.

The non-“existential” protocol issue is actually separate. We can illustrate the issues with far simpler protocols:

	protocol P { }
	protocol Q : P { }
	protocol R { }
	protocol S { }

	extension P : R { } // #1: every P is also an R
	extension R : S { } // #2: every R is also an S

if I then ask the question “is some Any value an S?":

	func f(x: Any) {
		if let xs = x as? S { … }

what does it take to make that code produce the right answer for, e.g.,

	struct MyStruct : Q { }


Well, at runtime, you start by asking “is MyStruct an S?” It is not directly an S, but...
	- we know from #2 that every R is an S. “Is MyStruct an R?” It is not directly an R, but…
	- we know from #1 that every P is an R. “Is MyStruct a P?” Ah hah! It is a P because MyStruct declares conformance to Q, and every Q is a P.

So now we need to pull together a “MyStruct as an S” representation—at runtime—and cache it so we don’t have to go through all of that work the next time one asks that question. It’s absolutely implementable, but having to do that potentially-slow search at runtime is a major concern, particularly because adding a new extension that makes one protocol conform to another at any point in the system can cause widespread performance effects.

	- Doug

More information about the swift-evolution mailing list