How to break outer loops from inner structures that respond break (loops/switch)

与世无争的帅哥 提交于 2019-11-26 19:32:54

问题


How to I break an outer loop from within an nested structure that responds to the break statement in Swift?

For example:

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

The break will only get me out of the switch, and in Swift, it has to be used as empty cases are not allowed. How can I entirely exit the loop from within the switch?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/24049629/how-to-break-outer-loops-from-inner-structures-that-respond-break-loops-switch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!