Swift should allow equality tests of enums with associated values

Originator:jlieske
Number:rdar://17408414 Date Originated:21-Jun-2014 01:09 PM
Status:Duplicate Resolved:
Product:Developer Tools Product Version:Xcode6 beta: Version 6.0 (6A216f)
Classification:Enhancement Reproducible:Always
 
Enums with associated values can be tested and decomposed through switch statements. However, there are situations where simpler equality tests are important, such as in unit tests.  

At present, Swift does not automatically implement an equality operator for enums, even when the associated values are all supported by the equality operator.  For example, the code:

enum SimpleToken {
    case Name(String)
    case Number(Int)
}
let t1 = SimpleToken.Number(123)
let t2 = SimpleToken.Number(123)
XCTAssert(t1 == t2)

fails with the error:
error: could not find an overload for '==' that accepts the supplied arguments
    XCTAssert(t1 == t2)
    ^~~~~~~~~~~~~~~~~~~

The programmer can manually implement an overload of the equality operator, but the code is 100% boilerplate.  

I propose that the compiler generate an equality test for enums when all associated values support equality tests.  I believe this is a type-safe operation, as other functional languages like Scala and Ocaml support equality tests of their sum types.  It should not add any overhead to programs that don't need equality tests.  If there is a concern about that, it would be accessible for the program to opt-in to equality tests via some source code declaration (e.g. implementing a protocol or including and attribute like @eqtype).

Comments

Duplicate of 19525557 (Open)


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!