Simple use of switch:
In contrast to the switch statements in C and OBJECTIVE-C, the switch statement in Swift does not drop to the next case under each case by default. Instead, the first matching switch statement finishes when the first matching case is completed. became the whole of its execution. Instead of requiring a definite break statement. This makes the switch statement more secure, simpler than the use of the C language, and avoids the wrong execution of multiple case.
Learn from Examples:
Let Anothercharacter:character = ' A ' switch anothercharacter {case ' a ': println ("a") case "a": println ("the Letter was A ") default: println (" Not Letter ")}
By playground in Swift, you can see that the above code outputs: "A"
Explain the book "a" character: Define a Anothercharacter constant character in the program, judge it by the case in the switch statement, and when it encounters with the first one, it is what we want to find, and then executes the corresponding code block output "a" Character.
Note: Each case statement contains at least one executable statement, or the program is not valid
A case can be matched with multiple objects, separated by commas:
Switch Anothercharacter {case "B", "C", "D": println ("Output BCD") case "a", "E", "F": println ("Output AEF") Default: println ("not Found") the}//program outputs: Output AEF
Because when executing the program, compared with the three objects in the first case, we find that we do not want it, and then we execute the second case and compare it with the multiple objects.
Tuples in switch are used:
Write a simple example: use a point coordinate (x, y) to represent a simple tuple (int,int) and classify it in the diagram later in the example
Let Originpoint = (1, 1) switch originpoint{case (0,0): println ("(0,0) was at the origin") case (_,0): println ("(\ (O riginpoint.0), 0) is on the x-axis ") Case (0,_): println (" (0, \ (originpoint.1)) are on the y-axis ") Case ( -2...2,-2...2): println ("(\ (originpoint.0), \ (Originpoint.1)) is inside the box") Default: println ("(\ (originpoint.0), \ ( Originpoint.1)) is outside of the box ") }//Output:" (1, 1) is inside the box "
The corresponding description: (_,0) and (0,_) in the "_" symbol in Swift represents the omission of the meaning, ( -2...2,-2...2) in the X value in the interval [ -2,2], Y value in the range [ -2,2].
Learn about switch in Swift