How to break outer loops from inner structures tha

2019-01-21 21:27发布

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条回答
成全新的幸福
2楼-- · 2019-01-21 21:54

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
    }
}
查看更多
登录 后发表回答