[swift-evolution] Swift 3 Generics

Matthew Johnson matthew at anandabits.com
Thu Dec 17 12:03:08 CST 2015


> On Dec 17, 2015, at 11:54 AM, Douglas Gregor <dgregor at apple.com> wrote:
> 
>> 
>> 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 { }
> 	f(MyStruct())
> 
> ?
> 
> 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.

Couldn’t this work theoretically be done as part of whole program optimization at some point in the future?  Would that add too much potentially unnecessary metadata to the binary?  Is there some other reason that wouldn’t be possible?

Matthew

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151217/92177104/attachment.html>


More information about the swift-evolution mailing list