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

前端 未结 2 1187
逝去的感伤
逝去的感伤 2020-12-13 05:36

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

For example:

while someCondi         


        
相关标签:
2条回答
  • 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
        }
    }
    
    0 讨论(0)
  • 2020-12-13 06:17

    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
                } 
            } 
    
    0 讨论(0)
提交回复
热议问题