How to Bind a Variable to Multiple Alternatives in a Switch Statement

Is there a way to bind a variable to multiple alternatives in a switch statement?

The Swift evolution Proposal SE-0043 that has been accepted fixed this issue with Swift 3.

enum Response {
case result(String, Int)
case error(String)
}

let resp = Response.error("Some text")

switch resp {
case let .result(str, _), let .error(str):
print("Found: \(str)") // prints Found: Some text
}

With Swift 2, the previous Playground code would generate an error: case labels with multiple patterns cannot declare variables. However, with Swift 3, it generates no errors and has the expected behavior.

Switch statement for multiple cases in JavaScript

Use the fall-through feature of the switch statement. A matched case will run until a break (or the end of the switch statement) is found, so you could write it like:

switch (varName)
{
case "afshin":
case "saeed":
case "larry":
alert('Hey');
break;

default:
alert('Default case');
}

Pattern match and conditionally bind in a single Switch statement

Sure, you can use the conditional casting pattern case let x as Type:

let x: Any = "123"

switch x {
case let s as String:
print(s) //use s
case let i as Int:
print(i) //use i
case let b as Bool:
print(b) //use b
default:
fatalError()
}

Replacements for switch statement in Python?

The original answer below was written in 2008. Since then, Python 3.10 (2021) introduced the match-case statement which provides a first-class implementation of a "switch" for Python. For example:

def f(x):
match x:
case 'a':
return 1
case 'b':
return 2
case _:
return 0 # 0 is the default case if x is not found

The match-case statement is considerably more powerful than this simple example.


You could use a dictionary:

def f(x):
return {
'a': 1,
'b': 2,
}[x]

Can the switch statement have more than one variable?

Yes/No.

No traditional language with a "switch" statement has this. It does exist in something called "pattern matching".

C#, Java, PHP, and Python do not support pattern matching (not completely sure about PHP, but I don't believe it does. Correct me if I'm wrong).

Here's an example in Haskell where pattern matching does exist. Pattern matching is in a lot of functional style languages.

function 1 _ = "first parameter has a one"
function _ 1 = "second parameter is a one"
function _ _ = "I don't know what crazy number you passed in"

When that function is called, the runtime/compiler/whoever checks it will see if the first function can be called. If it can, it returns that value. It then keeps going until it can find some match that works for the given parameters. The "_" is just a way of saying, "anything can be here, and I really don't care what it is so don't bind the value to a name". If I cared about the value, I could do:

function 1 a = "second parameter is " ++ (show a)

Now since it usually goes top-down (unlike the switch statement), this is more akin to an if/else than a switch statement which just jumps to the correct spot. It's just a very nice looking if/else. Also, if I reordered it so the most general case was at the top of the file, the other cases would be ignored.

You can also do something similar with templates, but that will only work at compile time.

Simplify switch statement for multiple control

You can get a reference to the control using FindName

var checkbox = this.FindName($"checkbox{num}") as CheckBox;
checbox.IsChecked = true;

dynamical binding or switch/case?


from the view point of DESIGN PATTERN, which one is better?

Using polymorphism (Solution 1) is better.

Just one data point: Imagine you have a huge system built around either of the two and then suddenly comes the requirement to add another type. With solution one, you add one derived class, make sure it's instantiated where required, and you're done. With solution 2 you have thousands of switch statements smeared all over the system and it is more or less impossible to guarantee you found all the places where you have to modify them for the new type.

from the view point of RUNTIME EFFCIENCE, which one is better? Especailly as the kinds of Object

That's hard to say.

I remember a footnote in Stanley Lippmann's Inside the C++ Object Model, where he says that studies have shown that virtual functions might have a small advantage against switches over types. I would be hard-pressed, however, to cite chapter and verse, and, IIRC, the advantage didn't seem big enough to make the decision dependent on it.

Java switch statement multiple cases

Sadly, it's not possible in Java. You'll have to resort to using if-else statements.

Javascript scope variable to switch case?

Since var creates variables at function scope anyway, using it is pretty pointless. For this to work at a granularity below function scopes you'll have to use let and a browser/compiler which supports it, and then introduce a new block which you can scope things to (within switch it's simply invalid syntax):

if (true) {
let s;

switch (i) {
...
}
}

This scopes s to the if block, which for all intents and purposes is identical to the "switch scope" here.

If you cannot support let, you'll need to use an IIFE:

(function () {
var s;

switch (...) ...
})();

Possible to fall through an enum case but still use its associated value?

You cannot use fallthrough here, however you can match multiple cases with associated values, and bind the associated value(s) as long as the patterns for each of the variable bindings match, and the value(s) bound for each pattern share the same type(s) – as per SE-0043.

Therefore you can just say:

switch result {
case .success:
print("success")
case .failure(let errorMessage), .reauthenticate(let errorMessage):
print(errorMessage)
}


Related Topics



Leave a reply



Submit