Sunday, November 29, 2015

Covariance and Contravariance

Mike Ash:

Covariance is when subtypes are accepted. Overridden read-only properties are covariant.

Contravariance is when supertypes are accepted. The parameters of overridden methods are contravariant.

Invariance is when neither supertypes nor subtypes are accepted. Swift generics are invariant.


Swift generics are normally invariant, but the Swift standard library collection types — even though those types appear to be regular generic types — use some sort of magic inaccessible to mere mortals that lets them be covariant.


There is an interesting problem with generic collection covariance: it potentially allows objects of the wrong type to be inserted in the collection.

I’m told that the first version of Java had covariant arrays without sufficient protection, which allowed to downcast objects without compile time or runtime checks[…]


Fortunately, with Swift’s copy-on-write arrays, this code is perfectly fine: the assignment of animals[0] will create a copy of the array, so cats will still only contain Cats.

Comments RSS · Twitter

Leave a Comment