[swift-evolution] [Manifesto] Completing Generics

Slava Pestov spestov at apple.com
Thu Mar 3 00:59:29 CST 2016


> On Mar 2, 2016, at 10:45 PM, Brent Royal-Gordon <brent at architechies.com> wrote:
> 
>>> if let storedInE1 = e1 openas T {     // T is a the type of storedInE1, a copy of the value stored in e1
>>>  if let storedInE2 = e2 as? T {      // is e2 also a T?
>>>    if storedInE1 == storedInE2 { … } // okay: storedInT1 and storedInE2 are both of type T, which we know is Equatable
>>>  }
>>> }
>> 
>> I’m worried that this is not really correct with inheritance. If e1 is an instance of SubClass, and e2 is an instance of SuperClass with SubClass : SuperClass, then your operation is no longer symmetric. Heterogeneous equality just seems like a pain in general.
> 
> Following from the generic constants mentioned earlier, perhaps this is expressed with some kind of generic `if let`?
> 
> 	func == (e1: Any<Equatable>, e2: Any<Equatable>) -> Bool {
> 		guard let concreteE1<T: Equatable> = e1 as? T, concreteE2 = e2 as? T else {

I think here the generic signature should really come first before any patterns, so more like ‘guard let <T : Equatable> …'.

But this is rather complicated. I fear. Perhaps a well-crafted one-off language feature to handle heterogeneous equality is better.

Here’s a really not-serious proposal: it seems we could implement GADTs if we allowed enum cases to have generic parameter lists, and extended pattern matching as above.

enum Foo {
	case Something<T>(T)
	case Nothing
}

let a: [Foo] // could contain many different Something types

Slava

> 			return false
> 		}
> 		
> 		// If we made it through that `guard`, there is some `Equatable` type `T` which `e1` 
> 		// and `e2` both contain.
> 		// (However, I'm not sure why this type couldn't be `Any<Equatable>`.)
> 		
> 		return concreteE1 == concreteE2
> 	}
> 
> -- 
> Brent Royal-Gordon
> Architechies
> 




More information about the swift-evolution mailing list