Conditional switch Statements in Swift switch...case Learning tutorial _swift

Source: Internet
Author: User
Tags error code

Grammar
syntax for switch statements in the Swift language:

Copy Code code as follows:

Switch Expression {
Case expression1:
Statement (s)
Fallthrough/* Optional *
Case Expression2, Expression3:
Statement (s)
Fallthrough/* Optional *

Default:/* Optional *
statement (s);
}




Note: In most languages, in a switch statement block, the case is followed by a break, otherwise the statement after the case will run sequentially, and in the Swift language the default will not be performed and the switch will terminate. You need to use the Fallthrough statement if you want the statements after the case to continue to run sequentially in Swift.


Here are two points to note:


Switch of course also supports explicit break, which is usually the only way you do it, and that is when you don't want to do anything in default, you can explicitly add a break in default.


Fallthrough is not effective under any circumstances, and when you use value binding technology in a switch, Fallthrough is banned. The Value binding is mentioned below.

Supports multiple data types
in Objective-c, a switch statement can only support shaping data (or a character), but in Swift, a switch can support a variety of data types, including floating-point, Boolean, string, and so on:
Support for floating point:

Copy Code code as follows:

let float = 1.5
Switch float {
Case 1.5:
"1.5"//IS output
Default
"Default"
}



Support Boolean:


Copy Code code as follows:

Let issuccess = True
Switch Issuccess {
Case true:
"True"//IS output
Default
"Default"
}



Support string:


Copy Code code as follows:

Let name = "Bannings"
Switch name {
Case "Bannings":
"Bannings"//IS output
Default
"Default"
}



It could be said to be the most data-type switch in history.

Support Interval Operators
not only can the loop structure be used in the interval operator, but also the interval operator can be used in the switch:

Copy Code code as follows:

var i = 15
Switch I {
Case 0 ... 10:
"0~10"
Case 11 ... 20:
"11~20"//IS output
Default
"Default"
}



Is it cool to do a batch match for a range of values? Floating-point numbers also support interval operators.

Support tuples
as a greatly enhanced switch, tuples are also supported:

Copy Code code as follows:

Let request = (true, "success")
Switch Request {
Case (True, "success"):
"Success"//IS output
Case (False, "failed"):
"Failed"
Default
"Default"
}



Using tuples is consistent with other data types, but tuples also have one feature that you can use to skip over values you don't care about, such as:


Copy Code code as follows:

Let (name, _, age) = ("Bannings", true, 22)



This feature is also supported when using switch:


Copy Code code as follows:

Let request = (true, "success")
Switch Request {
Case (_, "Success"):
"Success"//IS output
Case (False, _):
"Failed"
Default
"Default"
}



Skip over values that you don't care about, just meet another value. It is important to note that if the value in the tuple is also a numeric type, it is also possible to use the interval operator:


Copy Code code as follows:

Let request = (Ten, "failed")
Switch Request {
Case (_, "Success"):
"Success"
Case (1 .....) 10, _):
"1~10"//IS output
Default
"Default"
}



Value Binding


For tuples, switch also supports value Binding similar to optional Binding, which extracts the values from the tuples and uses them directly below:


Copy Code code as follows:

Let request = (0, "success")
Switch Request {
Case (0, let State):
State//Output: Success
Case (Let ErrorCode, _):
"Error code is \ \ (errorcode)"
//covers all possible case, no need to write default



This is also possible:


Copy Code code as follows:

Let request = (0, "success")
Switch Request {
Case let (errorcode, state):
State//Output: Success
Case (Let ErrorCode, _):
"Error code is \ \ (errorcode)"
}



It is equivalent to put let on the outside and put it on the inside for each element to be written separately.


When you use value binding in a case, if you also use Fallthrough in one of its previous cases, which is not allowed by the compiler, you may receive a compilation error:





As long as the following errorcode removed on the line, of course, consider their own logic.

Support for additional logical judgments
When you use a switch statement, the switch is properly directed to the appropriate case section, which is equivalent to making a logical decision, but Swift's switch statement also supports additional logical judgments:

Copy Code code as follows:

Let request = (0, "success")
Switch Request {
Case (0, let state) where state!= "success":
State
Case (Let ErrorCode, _):
"Error code is \ (errorcode)"//Output: "Error code is 0"
}



This is also cool, I believe in some cases will be very useful.

Summarize
Swift has greatly enhanced the switch, making the switch more flexible, which is an exciting change, but if you don't control the changes, it may make you more difficult to troubleshoot and make your code more complex. It is always useful to be flexible and to keep your head clear when appropriate.

Related Article

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.