如何从响应中断的内部结构中断外部循环(循环/切换)


78

如何在响应breakSwift中的语句的嵌套结构中打破外部循环?

例如:

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,而在斯威夫特,它具有为空的情况下不得使用。如何完全从中退出循环switch

Answers:


165

Swift允许带标签的语句。使用标记的语句,break无论嵌套循环的深度如何,您都可以指定要从哪个控制结构开始(尽管从可读性的角度来看,通常嵌套越少越好)。这也适用于continue

例:

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
    }
}

2

将循环标记为outerLoop,并在需要时用户中断标签:即在我们的情况下中断outerLoop。

outerLoop: for indexValue in 0..<arr.count-1 {
            if arr[indexValue] > arr[indexValue+1] {
                break outerLoop
            } 
        } 
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.