Tips for Switch Statements _swift

Source: Internet
Author: User

Overview

The switch statement evaluates to an expression, compares the result with the case child, and, if it matches, executes down from the statement at which it was executed.

Grammar

break; The statement is optional, and if a break is encountered, the entire switch statement is jumped out. If there is no case match, go to the branch of default: Default: The branch is also optional.

switch (expression) {
case value1:
//When the result of expression matches value1, start statements1 from this place
;
[break;]
Case value2:
//When the results of the expression match with the value2, the statements2 is executed from here
;
[Break;]
...
Case Valuen:
//When the results of the expression match with the Valuen, the STATEMENTSN is executed from here
;
[Break;]
Default:
//If expression does not match the value above, execute the statement
statements_def here;
[Break;]
}

Judging the conditions of use in case

Look at the following code, which displays alert when Foo is 0,1,2,3.

var foo = 1;
Switch (foo) {case
0: Case
1: Case
2: Case
3:
alert (' yes ');
break;
Default:
alert (' not ');

Is there any better way to spell it? The following is obviously more concise and clear.

var foo = 1;
Switch (TRUE) {//non-variable true replaces foo case
foo >= 0 && foo <= 3:
alert (' yes ');
break;
Default:
alert (' not ');

Presentation level

Carefully designed switch put _ at least the most rare conditions _ above, the normal conditions placed in the position relative to the following

function Rankprogrammer (rank) { 
switch (rank) {Case 
"advanced": 
this.secretary = true;
Case "Intermediate": 
This.laptop = true;
This.bonus = true;
Case "PRIMARY": 
this.salary = true;
This.vacation = true; 
}
}
var xiaohu=new rankprogrammer ("advanced");
Console.log (Xiaohu);

The above content has introduced the switch statement the skill, hoped for everybody above help.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.