[swift-evolution] Equality of enum with payload
Jérôme Duquennoy
jerome+swift at duquennoy.fr
Fri Dec 11 09:56:34 CST 2015
Hi everyone,
In swift, enums are much much more powerful than they used to be in c, c++ or objective-c.
One of their great feature is to be able to carry a payload.
Sadly, even a simple payload makes comparison much more complicated.
Consider this code :
----------------------------------------------------------------------
enum MyEnum {
case One
case Two
}
let const1 = MyEnum.One
let const1bis = MyEnum.One
const1 == const1bis // -> true
----------------------------------------------------------------------
It compiles fine, and is pretty concise.
Let’s add a payload to the enum
----------------------------------------------------------------------
enum MyEnumWithPayload {
case One(payload: String)
case Two(payload: String)
}
let simplePayload = "test"
let const1 = MyEnumWithPayload.One(payload: simplePayload)
let const1bis = MyEnumWithPayload.One(payload: simplePayload)
const1 == const1bis // error : Binary operator '==' cannot be applied to two MyEnumWithPayload operand
----------------------------------------------------------------------
This does not compile.
An equality operator is needed to handle that case :
----------------------------------------------------------------------
func ==(leftToken: MyEnumWithPayload, rightToken: MyEnumWithPayload) -> Bool {
var result: Bool = false;
switch(leftToken, rightToken) {
case (let .One(leftPayload), let .One(rightPayload)):
result = (leftPayload == rightPayload)
case (let .Two(leftPayload), let .Two(rightPayload)):
result = (leftPayload == rightPayload)
default:
result = false;
}
return result;
}
----------------------------------------------------------------------
I have two concerns with that :
- the added code is much bigger than the declaration of the enum, and the added code is not that simple to read. It is pretty simple to understand, but I find it complex to read.
- we have to use a default, otherwise, the compiler complains that the enum is not exhaustive (my compiler is configured to treat warnings as errors). So if we add a new value to the enum, we will not get a compiler warning reminding us that we should deal with equality for the new case.
It would be great to have a default equality operator for enums with a payload, as we have for the simple enum.
The logic of it would be : if the case is the same, and the payload(s) of each operand are equal, then the two operands are equal.
Of course, an equality operator has to be defined for the types of the payloads.
Jerome
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151211/14a4c22d/attachment.html>
More information about the swift-evolution
mailing list