[swift-evolution] Covariance and Contravariance

André Videla zephyz at me.com
Wed Dec 9 04:11:39 CST 2015


> On 09 Dec 2015, at 09:04, John McCall via swift-evolution <swift-evolution at swift.org> wrote:
> 
> One challenge here is that subtyping in Swift doesn’t mean equivalence of representation.

I’m curious, what does that mean?
In my experience," Int <: Int?" means Int can be used when "Int?" is expected.
Imagine this scenario:

class A {}
class B {}
class C : A {}
class D : B {}

func processDict(d: [C : B]) {}

let dict1 = [C: B]()
let dict2 = [A: D]()  //dict 2 <: dict1
processDict(dict1)
processDict(dict2)

I get a type error when it should type check. Because it is safe to output D wherever I expect a B and It is safe to use A whenever I need to input a C.

About your example on covariant arrays: Variance on arrays depends on if they are read only or read and write.
Read and write arrays need to be invariant to be safe. But read-only arrays can be covariant. If the compiler can make this distinction, it seem reasonable to assume it can eagerly do the transformation at no runtime cost.

- André
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151209/f7d8a602/attachment.html>


More information about the swift-evolution mailing list