Andrea Andrea - 5 months ago 34
Swift Question

Swift use of break in guard statement

I'm trying to use

break
in an
guard
statement, but the compiler tells me


'break' is only allowed inside a loop, if, do, or switch


Is possible to write something like in this snippet?

func test(string: String?, x: Int) {
print("Function Scope BEGIN")
if x > 4 {
guard let pr = string else { break }
print(pr)
}
else {
print("Not")
}
print("Function Scope END")
}

Answer

Yes it is possible. You can use unlabeled break statements inside loops, but not inside a if block. You can use labeled break statements though. For example, this version of your code will work:

func test(string: String?, x: Int) {
    print("Function Scope BEGIN")
    someLabel: if x > 4 {
        guard let pr = string else { break someLabel }
        print(pr)
    }
    else {
        print("Not")
    }
    print("Function Scope END")
}
Comments