In Swift's switch, the case is followed by the use of Fallthrough, which is the same as the usage without break after OC case!
The use of Fallthrough should be noted:
1. When Fallthrough is added, the following case or default statement will be run immediately, regardless of whether the condition is satisfied or not
var age = 10
switch age {
case 0 ... 10:
print ("little friend")
fallthrough
case 11 ... 20:
print ("big friend")
case let x:
print ("\ (x) year-old friend")
}
// Output result:
Children
Big friend
2. After adding the Fallthrough statement, the "following next" case condition cannot define constants and variables
var age = 10
switch age {
case 0 ... 10:
print ("little friend")
fallthrough // Report error here
case let x:
print ("\ (x) year-old friend")
}
// The program reports an error:
‘Fallthrough’ cannot transfer control to a case label that declares variables
The reason, I understand is: by the 1th we know that the first case after the execution (the output "children") will directly execute the next case, and the next scenario defines a temporary variable x, so that the direct from the previous cases come in without this variable x, If x is used in the case statement, it will obviously go wrong. Swift is a language that requires security, which is not allowed to happen, so it is not allowed to define constants/variables in a case condition after fallthrough--except for the next one followed, the other case can define constants/variables
3. After executing the Fallthrough, jump directly to the next conditional statement, the statement after the condition execution statement does not execute
var age = 10
switch age {
case 0 ... 10:
print ("little friend")
fallthrough
print ("I jumped") // This sentence was not executed
case 11 ... 20:
print ("big friend")
case let x:
print ("\ (x) year-old friend")
}
// Output result:
Children
Big friend
If you have any questions, please leave a message to tell me!
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
In Swift's switch structure, the usage of the Fallthrough note summarizes