How to access switch results of a case?
The example is so contrived that it's not at all helpful. Consider this
enum ServerResponse {
case Result(String, String)
case Error(String)
}
for i in 1...100 {
let mySuccess: ServerResponse = {
let zeroOrOne = rand() % 2
if zeroOrOne == 0 {
return ServerResponse.Result("7:00 am", "8.09 pm")
} else {
return ServerResponse.Error("Out of cheese.")
}
}()
var serverResponse: String
switch mySuccess {
case let .Result(sunrise, sunset):
serverResponse = "Sunrise is at \(sunrise) and sunset as \(sunset)"
case let .Error(error):
serverResponse = "Failure... \(error)"
}
println(serverResponse)
}
The gist is that the 'success' variable in the example should really be an assignment as a result of some function / subsystem call. I wrapped it in a loop for println() clarity
How to get return value from switch statement?
That's because when you're putting that into the Chrome console, you're short-circuiting it. It's just printing 'OK' because it's reaching the default case, not actually returning something.
If you want something returned, stick it in a function, and return the 'OK' from in the default case.
function switchResult(a){
switch(a){
default:
return "OK";
}
}
var a = switchResult(3);
Switch Statement - Multiple results for single case
You could use an array of messages :
var messages = ["message 1...", "message 2...", "message 3...", "message 4...", "message 5..."]
Then use the count
variable as the index
of this array to show the messages one after other.
NOTE: You must init the count
to the default value 0
in case the user typed something so the next empty submit will show the first message in index 0
.
var count = 0;var messages = ["message 1...", "message 2...", "message 3...", "message 4...", "message 5..."];
function switchStatement() { var text; var answers = document.getElementById("userInput").value;
switch (answers) { case "": text = messages[count]; count = count < messages.length - 1 ? count + 1 : 0; break; default: text = "Good job!"; count = 0; } document.getElementById("feedback").innerHTML = text; document.getElementById("userInput").value = "";}
<p>Please write something down and press "enter".</p>
<input id="userInput" type="text" onKeyDown="if(event.keyCode==13) switchStatement();">
<p id="feedback"></p>
why I get Different result in switch statements
When you do
switch(bill){
a case
will be fulfilled if the expression that follows it is ===
to the value of bill
. For example, if bill
is 124
, then switch(bill)
would require
case: 124:
tip = bill * .15 // because 124 <= 200
for your program to work as expected. Your code is producing unexpected results because all the case
s fail, and it falls through to the default
.
The switch(true)
works because when you have cases of
case bill > 0 && bill < 50:
this will effectively evaluate to
case true
// block below will run, because `true` is `===` to the expression that was switched against
or
case false:
// block below will not run, because `false` is `!==` to the expression that was switched against
and run the case block accordingly.
switch
is not the right tool for the job, IMO - it's confusing and verbose. (It's never the right tool for any programming task in Javascript, I think.) I'd use if
/else
instead:
const getTip = (bill) => { if (bill > 0 && bill < 50) { return bill * 0.2; } else if (bill >= 50 && bill <= 200) { return bill * 0.15; } else { return bill * 0.1; }};
function simpleTipCalculator(bill) { console.log(getTip(bill));}
simpleTipCalculator(124)simpleTipCalculator(48)simpleTipCalculator(268)
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');
}
Using two values for one switch case statement
You can use have both CASE
statements as follows.
case text1:
case text4:{
//blah
break;
}
SEE THIS EXAMPLE:The code example calculates the number of days in a particular month:
class SwitchDemo {
public static void main(String[] args) {
int month = 2;
int year = 2000;
int numDays = 0;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
numDays = 31;
break;
case 4:
case 6:
case 9:
case 11:
numDays = 30;
break;
case 2:
if (((year % 4 == 0) &&
!(year % 100 == 0))
|| (year % 400 == 0))
numDays = 29;
else
numDays = 28;
break;
default:
System.out.println("Invalid month.");
break;
}
System.out.println("Number of Days = "
+ numDays);
}
}
This is the output from the code:
Number of Days = 29
FALLTHROUGH:
Another point of interest is the break statement. Each break statement
terminates the enclosing switch statement. Control flow continues with
the first statement following the switch block. The break statements
are necessary because without them, statements in switch blocksfall
: All statements after the matching case label are executed in
through
sequence, regardless of the expression of subsequent case labels,
until a break statement is encountered.
EXAMPLE CODE:
public class SwitchFallThrough {
public static void main(String[] args) {
java.util.ArrayList<String> futureMonths =
new java.util.ArrayList<String>();
int month = 8;
switch (month) {
case 1: futureMonths.add("January");
case 2: futureMonths.add("February");
case 3: futureMonths.add("March");
case 4: futureMonths.add("April");
case 5: futureMonths.add("May");
case 6: futureMonths.add("June");
case 7: futureMonths.add("July");
case 8: futureMonths.add("August");
case 9: futureMonths.add("September");
case 10: futureMonths.add("October");
case 11: futureMonths.add("November");
case 12: futureMonths.add("December");
default: break;
}
if (futureMonths.isEmpty()) {
System.out.println("Invalid month number");
} else {
for (String monthName : futureMonths) {
System.out.println(monthName);
}
}
}
}
This is the output from the code:
August
September
October
November
December
Using Strings in switch Statements
In Java SE 7 and later, you can use a String object in the switch
statement's expression. The following code example, ,
displays the number of the month based on the value of the String
named month:
public class StringSwitchDemo {
public static int getMonthNumber(String month) {
int monthNumber = 0;
if (month == null) {
return monthNumber;
}
switch (month.toLowerCase()) {
case "january":
monthNumber = 1;
break;
case "february":
monthNumber = 2;
break;
case "march":
monthNumber = 3;
break;
case "april":
monthNumber = 4;
break;
case "may":
monthNumber = 5;
break;
case "june":
monthNumber = 6;
break;
case "july":
monthNumber = 7;
break;
case "august":
monthNumber = 8;
break;
case "september":
monthNumber = 9;
break;
case "october":
monthNumber = 10;
break;
case "november":
monthNumber = 11;
break;
case "december":
monthNumber = 12;
break;
default:
monthNumber = 0;
break;
}
return monthNumber;
}
public static void main(String[] args) {
String month = "August";
int returnedMonthNumber =
StringSwitchDemo.getMonthNumber(month);
if (returnedMonthNumber == 0) {
System.out.println("Invalid month");
} else {
System.out.println(returnedMonthNumber);
}
}
}
The output from this code is 8.
FROM Java Docs
JavaScript: using a condition in switch case
This works:
switch (true) {
case liCount == 0:
setLayoutState('start');
var api = $('#UploadList').data('jsp');
api.reinitialise();
break;
case liCount<=5 && liCount>0:
setLayoutState('upload1Row');
var api = $('#UploadList').data('jsp');
api.reinitialise();
break;
case liCount<=10 && liCount>5:
setLayoutState('upload2Rows');
var api = $('#UploadList').data('jsp');
api.reinitialise();
break;
case liCount>10:
var api = $('#UploadList').data('jsp');
api.reinitialise();
break;
}
The only thing necessary is switch(true){...}
and for your case expressions to evaluate to booleans.
It works because, the value we give to the switch is used as the basis to compare against. Consequently, the case expressions, also evaluating to booleans will determine which case is run. Could also turn this around, and pass switch(false){..}
and have the desired expressions evaluate to false instead of true.. but personally prefer dealing with conditions that evaluate to truthyness. However, it does work too, so worth keeping in mind to understand what it is doing.
Eg: if liCount is 3, the first comparison is true === (liCount == 0)
, meaning the first case is false. The switch then moves on to the next case true === (liCount<=5 && liCount>0)
. This expression evaluates to true, meaning this case is run, and terminates at the break
. I've added parentheses here to make it clearer, but they are optional, depending on the complexity of your expression.
It's pretty simple, and a neat way (if it fits with what you are trying to do) of handling a long series of conditions, where perhaps a long series of ìf() ... else if() ... else if () ...
might introduce a lot of visual noise or fragility.
Use with caution, because it is a non-standard pattern, despite being valid code.
Related Topics
Error Domain=Nscocoaerrordomain Code=3840 "Invalid Value Around Character 0
Swiftui: Make Remaining Area of List Item Detect Clicks
Realm Write Transaction Failing, Despite Being in Transaction
Swiftsupport Folder Not Included in The IPA When Generating Build from Script
Why Does a Simple Swift Arithmetic Operation Compile So Slow
Swift Error "Static Member Cannot Be Used on Instance of Type"
Why Do I Get Rgb Values of (0,0,0) for an Nsimage with a Transparent Background
Reduce Float Precision Using Regexp in Swift
Appdelegate#Applicationdidfinishlaunching Not Called for Swift 4 Macos App Built from Command Line
Cannot Authenticate User for Aws Appsync with Swift Sdk
Can Not Get Correct Position of View in Swiftui
Swift Getnameinfo Unreliable Results for Ipv6
Applescript Email Attachment Not Working in Handler
I Opened My App in Xcode 10 and Now I Have Errors in 9.4.1: Sdkapplicationdelegate (Facebookcore)