如何打破外部循环从内部结构响应打破(循环/开关)

在 Swift 中,如何从响应 break语句的嵌套结构中切断外部循环?

例如:

while someCondition {
if someOtherCondition {
switch (someValue) {
case 0:     // do something
case 1:     // exit loop
case 2...5: // do something else
default:    break
}
} else {
someCondition = false
}
}

break只能让我离开 switch,而在 Swift 中,它必须被用作不允许使用的空格。如何完全从 switch中退出循环?

20696 次浏览

Swift allows for labeled statements. Using a labeled statement, you can specify which which control structure you want to break from no matter how deeply you nest your loops (although, generally, less nesting is better from a readability standpoint). This also works for continue.

Example:

outerLoop: while someCondition {
if someOtherCondition {
switch (someValue) {
case 0:     // do something
case 1:     break outerLoop // exit loop
case 2...5: // do something else
default:    break
}
} else {
someCondition = false
}
}

Label the loop as outerLoop and whenever needed user break Label: i.e. break outerLoop in our case.

outerLoop: for indexValue in 0..<arr.count-1 {
if arr[indexValue] > arr[indexValue+1] {
break outerLoop
}
}