[swift-evolution] Make generics covariant and add generics to protocols

Sune Foldager cyano at me.com
Mon Jan 18 11:08:34 CST 2016


> On 14 Jan 2016, at 00:02, Howard Lovatt <howard.lovatt at gmail.com> wrote:
> 
> Furthermore Microsoft chose to make Equatable<T> invariant. A strange choice heh. How come comparing using IComparable behaves differently than using Equatable? If you implement both, which Microsoft recommends, then you get invariance, because Equatable is invariant.

Actually, only the equality comparison part will be invariant. Generally, the APIs which call the IComparable and IEquatable methods are disjunct, so it’s not a problem in practice at all (comparable is almost only for sorting, equatable for putting in dictionaries and many other things). The reasoning for making Equatable invariant is explained on MSDN, but it has to do with what being equals means. It’s always a choice, of course.

At any rate, contravariance is definitely sometimes useful, and, I’d argue, just as often as covariance. Most of the time you don’t need either.

I personally regret that C# arrays are covariant (and so do the designers of C#), because it means more errors at runtime, maybe when the code is in production.

-Sune

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


More information about the swift-evolution mailing list