In the switch structure of Swift, note the usage of fallthrough. switchfallthrough
In the swift switch, the use of fallthrough is added after the case, which is the same as that of the case of OC without break!
Note the following when using fallthrough:
1. After fallthrough is added, the [followed by the next] case or default statement will be run directly, regardless of whether the conditions are met or not.
Var age = 10 switch age {case 0... 10: print ("kids") fallthrough case 11... 20: print ("friend") case let x: print ("\ (x) Friend")} // output result: Friend
2. After the fallthrough statement is added, the case condition cannot define constants and variables.
Var age = 10 switch age {case 0... 10: print ("") fallthrough // here error case let x: print ("\ (x) years old friend")} // program error: 'fallpass' cannot transfer control to a case label that declares variables
The reason is, I understand: we know from the first point that after the first case is executed (the output is "children"), the next case will be executed directly, the next case condition defines the temporary variable x, which leads to the absence of the variable x directly from the previous case. If the case statement uses x, obviously, an error occurs. A language that requires security such as swift naturally does not allow such a thing to happen. Therefore, constants/variables cannot be defined in the next case condition of fallthrough-except for the followed one, other cases can still define constants/variables (for example, the first code example)
3. After fallthrough is executed, it jumps directly to the next condition statement. The statements following the condition execution statement are not executed.
Var age = 10 switch age {case 0... 10: print ("") fallthrough print ("I jumped to") // This sentence is not executed case 11... 20: print ("friend") case let x: print ("\ (x) Friend")} // output result: Friend
If you have any questions, please leave a message to me!
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.