"where" on a switch case with multiple items is misleading

Consider:

switch x {
  case a, b where …: ...
}

this currently means:

switch x {
  case a where true, b where …: ...
}

Most people would probably think the “where" applies to both a and b.

To avoid this confusion, maybe if “where" is used for one item then it should be required for all items in that case?

4 Likes

Requiring “where" for all patterns seems like a good idea. I’ve run into this before.

Instinctively I tried to group using ( ), but then you’re matching tuples:

  case (a, b) where <where-expression>:

Having a way to apply the where-clause to all patterns would be nice. Maybe like this:

  case let a, b where all <where-expression>:

···

Consider:

switch x {
case a, b where …: ...
}

this currently means:

switch x {
case a where true, b where …: ...
}

Most people would probably think the “where" applies to both a and b.

To avoid this confusion, maybe if “where" is used for one item then it should be required for all items in that case?

1 Like

I just ran into this today. I had no idea that a where clause at the end of multiple case statements would only apply to the final one, especially when they’re written like this, one case on each line followed by a where clause:

switch foo {
case .a,
     .b,
     .c
     where someOtherVariable:
    break
}
1 Like

I pitched a potential solution for this problem: