[swift-users] Expression pattern cannot be a named tuple constant

Jordan Rose jordan_rose at apple.com
Wed Jul 6 12:26:01 CDT 2016

> On Jul 6, 2016, at 8:55, Neil Faiman <neil.swift at faiman.org> wrote:
> It’s actually more complicated than that.
> case (0, 0): is a tuple-pattern, so its interpretation is well defined. case int_1_1: must be an expression-pattern, since it does’t match any of the other pattern kinds. So it should compare the value of the pattern expression case_1_1 against the value of the switch expression (x, y).
> Now, the Swift Reference, in the Expression Patterns section, says
> The expression represented by the expression pattern is compared with the value of an input expression using the Swift standard library ~= operator. The match succeeds if the ~= operator returns true. By default, the ~= operator compares two values of the same type using the == operator. …
> If this were true, then my code would compile and work as I expected.
> But in fact, I observe that the expression int_1_1 == (x, y) compiles, but the expression int_1_1 ~= (x, y) gets the error “Binary operator ‘~=‘ cannot be applied to two ‘(int, int)’ operands.”
> This strongly suggests that the emphasized line in the Swift Reference quote does not correctly describe the language behavior — there is a bug either in the documentation (~= was not intended to be defined for tuple types) or in the standard library (~= was intended to be defined for tuple types, but never got implemented).

It's somewhere in between the two. More formally, "by default, ~= compares two values of the same type using a conformance to Equatable". Since tuples aren't named types, they don't conform to Equatable, and so we don't use their == operator.

We could fix this by adding overloads of ~= for tuples, by having the compiler fall back to == in switches, or by eventually allowing tuples to conform to Equatable if their elements do (somehow). Maybe there are other answers I haven't thought of, too.


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160706/1a5c7ae6/attachment.html>

More information about the swift-users mailing list