[swift-evolution] Covariance and Contravariance

John McCall rjmccall at apple.com
Wed Dec 9 16:15:26 CST 2015


> On Dec 9, 2015, at 11:50 AM, Michel Fortin <michel.fortin at michelf.ca> wrote:
> Le 9 déc. 2015 à 3:04, John McCall via swift-evolution <swift-evolution at swift.org> a écrit :
> 
>> One challenge here is that subtyping in Swift doesn’t mean equivalence of representation.  For example, Int is a subtype of Int?, but the later requires extra space to store in memory.  So while it would make sense to allow, say, [Int] to be a subtype of [Int?], the actual conversion at runtime wouldn’t be trivial — we’d either need to eagerly apply the element-wise transform, or Array would need some ability to apply it lazily.  Both come with fairly serious performance costs.
> 
> But the compiler already lets you use a [Derived] as a [Base?], as long as the representation is the same. It'd be nice if that could apply with generics too, even if the limitation was that it would work only as long as there is no difference in representation.

I was using Array as an example of a generic type, but I’d forgotten that we already had the subtyping rule in place as a special case there.

> If you want the restriction to depend a little less on low-level representation details, allow it only for class pointers. You won't have any representation problem there. This is also where people will expect it the most.

I’d rather we not design a general-purpose language mechanism that’s only actually useful for class pointers, especially given the importance of value types in the language.

John.


More information about the swift-evolution mailing list