Short answer: no way currently, you can only match one enum option in one place(not counting guarded options). So, duplicate your code for each enum option and live a happy life(this code will be also easier to read) or use a seconds switch(which might be shorter and easier in some more complex cases).
How to use switch with multiple enum values?
-
17-07-2023 - |
質問
I m trying this code:
enum SideType
{
Vex;
Cav;
Plano;
}
function drawLense(aLeftType:SideType){
switch (aLeftType)
{
case Cav:
leftCenter = -aRadius - d * 0.5;
case Vex:
leftCenter = -Math.cos(( -90 + offset) * Math.PI / 180) * aRadius-d*0.5;
case Plano:return ;
case Cav, Vex:
points1= drawCurve(1, -90 + offset + trim, 180 - offset * 2 - (trim * 2), leftCenter, aRadius);
_LB = points1[0];
_LA = points1[1];
}
}
But I get an error when compile:
characters 8-16 : This pattern is unused
So, it pointing at case Cav, Vex:
How can I check Cav or Vex in the case above?
EDIT
I found that if I removed case Cav & Case Vex, then case Cav, Vex will work, but this is not what I want, can't I repeat the pattern usage in an or experision? like (case Cav||Vex)?
case (Cav || Vex) would result into:
src/com/optics/components/Lense.hx:343: characters 8-38 : Case expression must be a constant value or a pattern, not an arbitrary expression
解決 3
他のヒント
There are only 3 choices for the value of aLeftType
, either Vex
, Cav
, or Plano
.
var aLeftType = Vex;
switch (aLeftType)
{
case Cav:
// If aLeftType is `Cav`, run this line.
case Vex:
// If aLeftType is `Vex`, run this line.
case Plano:
// If aLeftType is `Plano`, run this line.
case Cav, Vex:
// If aLeftType is `Vex` or `Plano`, run this line...
// But the first 2 cases already covered `Vex` and `Plano`,
// so it will never be reached.
}
So really, the code of the 4th case will never be run. It is similar to:
if (a == 1) {
trace("a is 1");
} else if (a == 1) {
trace("a is really 1"); // This can never be reached.
}
That means, you have to think again want do you really want to do.
Usually when you want to make the same thing in different situation, you make a function for that :)
function drawLense(aLeftType:SideType){
switch (aLeftType)
{
case Cav:
leftCenter = -aRadius - d * 0.5;
functionCalledIfCavOrVex();
case Vex:
leftCenter = -Math.cos(( -90 + offset) * Math.PI / 180) * aRadius-d*0.5;
functionCalledIfCavOrVex();
case Plano:return ;
}
}
function functionCalledIfCavOrVex(/*...*/){
points1= drawCurve(1, -90 + offset + trim, 180 - offset * 2 - (trim * 2), leftCenter, aRadius);
_LB = points1[0];
_LA = points1[1];
}
try:
case Cav | Vex:
trace("cav or vex");
Hope it helps.
所属していません StackOverflow