Swift 2的指南提到你可以结束if语句的程序执行。我个人从未使用if语句中断。
break语句结束循环的程序执行,if语句, 或者一个switch语句......当一个break语句后跟着 语句标签的名称,它结束循环的程序执行,如果 语句,或由该标签命名的switch语句。
在什么情况下会在if语句中使用break?这种语言功能似乎毫无用处。
TEST:
if (true) {
break TEST
}
答案 0 :(得分:14)
例如,如果你想用一组数字(偶数/有理数/负数)描述一个数字(带字符串),你的代码可能如下所示:
if condition1 {
// code
if condition2 {
// code
if condition3 {
// code
if condition4 {
//code
}
}
}
}
你可以通过重构(使用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
}
您可能认为这也可以通过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
}
答案 1 :(得分: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
}
但是在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
}
}
答案 2 :(得分:0)
我知道这是个老话题,但是刚才我使用break,这是必需的。 所以我的例子 我有对象的数组。 当用户点击一个单元格时,该单元格中的对象的i.parameter变为True。 我需要知道数组中的所有对象何时都具有i.parameter = True,这是停止游戏的条件。
func forTimer(){
for i in array {
if i.parameter = false
break
}
}
timer = Timer.scheduledTimer(timeInterval: 0.001, target: self, selector: #selector(forTimer), userInfo: nil, repeats: true)
即使一个i.parameter = false,我也不需要检查数组的其余部分。 该函数每毫秒被调用一次,因此我不必每毫秒检查一次整个数组。