Trung Kiên
Trung Kiên

Reputation: 185

Use switch statement with multiple variables

I want to use switch statement with 2 variables, for example, a and b, something like this:

switch(a,b){
  case(1,1): // a = 1 and b = 1
    doSomething()
    break
  case(1,2): // a = 1 and b = 2
    doSomethingElse()
    break
  case(0,2): // a = 0 and b = 2
    doOtherthings()
    break
  default
    doNothing()
}

I know this code doesn't work, so is there any alternative way to do this?

Upvotes: 2

Views: 4127

Answers (3)

Ned
Ned

Reputation: 236

The simplest answer would be to use a switch (true).

switch(true){
  case a === 1 && b === 1: // a = 1 and b = 1
    doSomething();
    break;
  case a === 1 && b === 2: // a = 1 and b = 2
    doSomethingElse();
    break;
  case a === 0 && b === 2: // a = 0 and b = 2
    doOtherThings();
    break;
  default:
    doNothing();
}

Upvotes: 0

ObiDan
ObiDan

Reputation: 131

It's absolutely possible, you just need to translate your tuple into a unique, scalar case.

For example, while I don't advise it, you could rewrite your example as such:

switch(a+':'+b){
  case('1:1'): // a = 1 and b = 1
    doSomething()
    break
  case('1:2'): // a = 1 and b = 2
    doSomethingElse()
    break
  case('0:2'): // a = 0 and b = 2
    doOtherthings()
    break
  default
    doNothing()
}

You could even build your cases dynamically from other variables, if you so choose, if you wanted to obfuscate it even more. :)

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386680

You could use if statements instead.

if (a === 1 && b === 1) doSomething();
else if (a === 1 && b === 2) doSomethingElse();
else if (a === 0 && b === 2) doOtherthings();
else doNothing();

Upvotes: -1

Related Questions