Swift 2 - Use case for using break on if statement? -
swift 2's guide mentions can end program execution of if statement. have never used break if-statement.
a break statement ends program execution of loop, if statement, or switch statement...when break statement followed name of statement label, ends program execution of loop, if statement, or switch statement named label.
in situation 1 using break in if-statement? language feature seems useless.
test: if (true) { break test }
using break if statement seems bit contrived, , can't think of place style demand it. does, however, save level of indentation when skipping latter portion of if statement in if-else clause, can useful nested loops.
in other languages, popular (and/or controversial) idiom use labels handling errors in nested functions. example, 1 might want break out of loop on error, this:
func testbreak3() { // doesn't compile!!! let = false, b = true, x = 10, y = 20, err = true if !a { if b && x > 0 { if y < 100 { if err { break handleerror } // statements } else { // other stuff } } } return // avoid error handling handleerror: print("error") // handle error }
but in swift (i'm using 2.0 reference), labels different other languages; above example doesn't compile 2 reasons: label isn't declared yet when it's used, , label must directly associated do
, while
, if
, or case
statement. furthermore, break within if
or do
statements requires statement labeled. can fix follows, although changes make solution less attractive due additional tracking via errorflagged
variable, making refactoring more attractive:
func testbreak() { let = false, b = true, x = 10, y = 20, err = true var errorflagged = false nestedif: if !a { if b && x > 0 { if y < 100 { if err { errorflagged = true break nestedif } // statements } else { // other stuff } } } // skip handling if no error flagged. if errorflagged { print("error") // handle error } }
Comments
Post a Comment