从 if 语句中断到 else 部分
Break from an if statement into the else section
我有一个if/else声明。
if (something) {
//run if logic
} else {
//run else logic
}
在我的 if logic phase
期间,我可能会发现一些让我想要 运行 我的 if/else 语句的 else 部分的东西。逻辑阶段太复杂,无法完全符合初始条件 something
.
是否有类似 break;
的内容可用于跳转到 if/else 语句的 else
部分。
我目前正在这样做,但我的团队不喜欢使用 goto
if (something) {
//run if logic
if (somethingComplex) {
goto elseSomething;
}
} else {
elseSomething:
//run else logic
}
再次注意,somethingElseComplex
是一个布尔状态,通过 运行 宁一些复杂的代码 big/multi-lined 以适应我的初始 if 条件,否则我会刚刚完成:if (something && somethingComplex)
,如果我在调用第一个条件之前计算 somethingComplex,我可能会得到假阳性结果。关于 !something
值
除了 goto
之外,没有任何语言功能允许您像这样任意转移控制权。
从代码中的两个位置移动到另一个位置的另一种更好的方法是使用过程:方法或函数。我认为在这里分解出 else
分支的内容是合适的。然后从内部 if
和 else
分支调用新过程。
您也可以考虑重构初始条件。应该有某种方法可以将这两项检查结合起来,而不必将它们粉碎到 if()
的 header.
的括号中
在 Objective-C 中,我会使用一个预先设置的布尔标志,而不是使用 if/else
而是两个单独的 if
语句,就像这样(这是 Swift代码,但结构相同):
var needToDoSomethingElseComplex = false
if something {
// do stuff
if somethingComplex {
needToDoSomethingElseComplex = true
}
}
if !something || needToDoSomethingElseComplex {
// do something else complex
}
但是 real Swift 会给你一个优雅的方式来做你正在寻找的东西 — switch
和 fallthrough
:
switch something {
case true:
print("hey")
if somethingComplex {
fallthrough
}
print("ho")
case false:
print("ha")
}
上面如果something
为真,如果somethingComplex
为真,我们就打印"hey"然后"ha",也就是流程你在找
那……
BOOL shouldGoToB = false;
if (a) {
//run if logic
if (somethingComplex) {
shouldGoToB = YES;
}
}
if (!a || shouldGoToB) {
}
我有一个if/else声明。
if (something) {
//run if logic
} else {
//run else logic
}
在我的 if logic phase
期间,我可能会发现一些让我想要 运行 我的 if/else 语句的 else 部分的东西。逻辑阶段太复杂,无法完全符合初始条件 something
.
是否有类似 break;
的内容可用于跳转到 if/else 语句的 else
部分。
我目前正在这样做,但我的团队不喜欢使用 goto
if (something) {
//run if logic
if (somethingComplex) {
goto elseSomething;
}
} else {
elseSomething:
//run else logic
}
再次注意,somethingElseComplex
是一个布尔状态,通过 运行 宁一些复杂的代码 big/multi-lined 以适应我的初始 if 条件,否则我会刚刚完成:if (something && somethingComplex)
,如果我在调用第一个条件之前计算 somethingComplex,我可能会得到假阳性结果。关于 !something
值
除了 goto
之外,没有任何语言功能允许您像这样任意转移控制权。
从代码中的两个位置移动到另一个位置的另一种更好的方法是使用过程:方法或函数。我认为在这里分解出 else
分支的内容是合适的。然后从内部 if
和 else
分支调用新过程。
您也可以考虑重构初始条件。应该有某种方法可以将这两项检查结合起来,而不必将它们粉碎到 if()
的 header.
在 Objective-C 中,我会使用一个预先设置的布尔标志,而不是使用 if/else
而是两个单独的 if
语句,就像这样(这是 Swift代码,但结构相同):
var needToDoSomethingElseComplex = false
if something {
// do stuff
if somethingComplex {
needToDoSomethingElseComplex = true
}
}
if !something || needToDoSomethingElseComplex {
// do something else complex
}
但是 real Swift 会给你一个优雅的方式来做你正在寻找的东西 — switch
和 fallthrough
:
switch something {
case true:
print("hey")
if somethingComplex {
fallthrough
}
print("ho")
case false:
print("ha")
}
上面如果something
为真,如果somethingComplex
为真,我们就打印"hey"然后"ha",也就是流程你在找
那……
BOOL shouldGoToB = false;
if (a) {
//run if logic
if (somethingComplex) {
shouldGoToB = YES;
}
}
if (!a || shouldGoToB) {
}