Boo*_*oon 17 if-statement break swift swift2
Swift 2的指南提到你可以结束if语句的程序执行.我个人从未使用if语句中断.
break语句结束循环,if语句或switch语句的程序执行......当break语句后跟语句标签的名称时,它结束循环的程序执行,if语句或switch语句命名通过那个标签.
在什么情况下会在if语句中使用break?这种语言功能似乎毫无用处.
TEST:
if (true) {
break TEST
}
Run Code Online (Sandbox Code Playgroud)
Qby*_*yte 14
例如,如果您想描述一个数字(带字符串)并引用数字集(偶数/有理数/负数),您的代码可能如下所示:
if condition1 {
// code
if condition2 {
// code
if condition3 {
// code
if condition4 {
//code
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
您可以通过重构(使用guard)来实现相同的逻辑但没有嵌套的ifs :
OuterIf: if condition1 {
// code
guard condition2 else { break OuterIf }
// code
guard condition3 else { break OuterIf }
// code
guard condition4 else { break OuterIf }
// code
}
// reads even better when breaking out of "do"
scope: do {
guard condition1 else { break scope }
// code
guard condition2 else { break scope }
// code
guard condition3 else { break scope }
// code
guard condition4 else { break scope }
// code
}
Run Code Online (Sandbox Code Playgroud)
你可能会认为这也与实现switch和fallthrough,而是因为它会检查所有条件,如果条件满足所有下列条件,甚至没有评估这不符合"正常"的情况下工作.
所以fallthough必须有条件地召唤.
这确实有效,但我不是很可读,更不用说它的"美"了:
let x = 4
switch x {
case _ where condition1:
// code
if condition2 { fallthrough }
case _ where false:
// code
if condition3 { fallthrough }
case _ where false:
// code
if condition4 { fallthrough }
case _ where false:
// code
break
default: break
}
Run Code Online (Sandbox Code Playgroud)
rho*_*mes 10
使用if语句的break似乎有点做作,我想不出样式会要求它的地方.但是,当在if-else子句中跳过if语句的后一部分时,它会保留额外的缩进级别,这对于深层嵌套循环非常有用.
在其他语言中,流行的(和/或有争议的)习语是使用标签来处理深层嵌套函数中的错误.例如,有人可能想要在出错时抛出循环,如下所示:
func testBreak3() {
// doesn't compile!!!
let a = false, b = true, x = 10, y = 20, err = true
if !a {
if b && x > 0 {
if y < 100 {
if err {
break handleError
}
// some statements
} else {
// other stuff
}
}
}
return // avoid error handling
handleError:
print("error")
// handle the error
}
Run Code Online (Sandbox Code Playgroud)
但是在Swift中(我使用2.0作为参考),标签与其他语言不同; 上面的例子不能编译,原因有二:当它使用的标签未声明的是,和标签必须与直接关联do,while,if,或case语句.此外,在一个if或多个do语句中断,需要对该语句进行标记.我们可以通过以下方式修复此问题,尽管由于通过errorFlagged变量进行额外跟踪,这些更改使解决方案的吸引力降低,从而使重构更具吸引力:
func testBreak() {
let a = false, b = true, x = 10, y = 20, err = true
var errorFlagged = false
nestedIf: if !a {
if b && x > 0 {
if y < 100 {
if err {
errorFlagged = true
break nestedIf
}
// some statements
} else {
// other stuff
}
}
}
// skip handling if no error flagged.
if errorFlagged {
print("error")
// handle error
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13154 次 |
| 最近记录: |