[swift-evolution] Equatability for enums with associated values

Derrick Ho wh1pch81n at gmail.com
Fri Jan 13 17:36:52 CST 2017


I think it is better to create a syntax for getting the associated values
and then comparing them.

enum Option {
case foo(String)
case bar(Int)
case zip
}

let op = Option.foo("hello")
let bb = Option.foo("world")

// proposed tuple-like syntax

op.foo.0 // returns Optional("hello")

// then we can compare values directly

if op.foo.0 == bb.foo.0 {
// ...
}

On Fri, Jan 13, 2017 at 5:44 PM Slava Pestov via swift-evolution <
swift-evolution at swift.org> wrote:

> On Jan 13, 2017, at 2:30 PM, David Sweeris via swift-evolution <
> swift-evolution at swift.org> wrote:
>
>
> On Jan 13, 2017, at 15:10, Anton Zhilin via swift-evolution <
> swift-evolution at swift.org> wrote:
>
> That seems pretty close to Rust’s derive. Why not invent a similar syntax
> in Swift? Otherwise it will make us look through all the sources to make
> sure deriving is used.
>
> enum Option: @derive Equatable {
>     ...
> }
>
> Also, we can get better looking compilation errors, like:
>
> ERROR at line 1, col 14: could not derive Equatable for Option
> enum Option: @derive Equatable {
>              ^~~~~~~~~~~~~~~~~
>
>
> I think that idea came up once before... can't remember where, though, or
> what we thought of it at the time.
>
> As far as reducing enum boilerplate, what about borrowing the generic
> system's syntax and looking at it from the switch's PoV?
> func == (lhs: MyEnum, rhs: MyEnum) -> Bool {
>     switch <c is MyEnum> (lhs, rhs) {
>     case (c(let lVal), c(let rVal)): // both lhs and rhs are "c" and the
> same case
>         return lVal == rVal //syntax error if `==` isn't defined for the
> associated value types of every case
>     default: return false
>     }
> }
>
>
> I think initially, we would like to implement deriving these witnesses
> directly in the compiler, instead of trying to come up with a
> metaprogramming syntax for them.
>
> Slava
>
>
> - Dave Sweeris
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
>
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170113/64110de2/attachment.html>


More information about the swift-evolution mailing list