有 2 个不同的嵌套循环,每个循环都有一个 Break 语句,用于在特定条件下中断外层循环。
我想知道如果我用相同的标题标记两个外部循环,这会引发break语句的困惑吗?
然后我尝试了以下代码片段
//#1
outterLoop: for x in 1...3 {
innerLoop: for y in 1...3 {
if x == 3 {
break outterLoop //break the "outterLoop"
} else {
print("x: \(x), y: \(y)")
}
}
}
//#2
outterLoop: for a in 1...3 {
innerLoop: for b in 1...3 {
if b == 3 {
break outterLoop //break the "outterLoop"
} else {
print("a: \(a), b: \(b)")
}
}
}
事实证明代码工作正常并且没有出现重新声明问题。我认为这可能与范围主题有关。 第一个break只能看到#1代码块中的outterLoop和第二个 em> break 只能在其所在的范围内看到 outterLoop,又称为 #2 代码块。结果,不可见的作用域限制了内部break可以“看到”的变量
问题:我理解正确吗?如果不是,请纠正我。即使我没有错,我相信我使用了非正式和不精确的描述。如果您能给我更正式和更准确的描述,那就太好了。
非常感谢
最佳答案
“The scope of a labeled statement is the entire statement following the statement label. You can nest labeled statements, but the name of each statement label must be unique.”
Excerpt From: Apple Inc. “The Swift Programming Language (Swift 2.2).” iBooks. https://itun.es/de/jEUH0.l
第一个 outterLoop:
标签的范围是第一个 for 循环,
第二个 outterLoop:
标签的范围是第二个
for循环。
因此第一个循环内的break outterLoop
只能引用
到第一个 outterLoop:
标签,对于
第二个循环。
这与 C 不同,其中 goto
语句及其目标标签
只需要在同一个函数中,因此不需要两个
可以在同一个函数中定义具有相同名称的标签。
关于swift - 不同的控制流语句可以有相同的标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39335088/