Search code examples
swiftif-statementoption-typeguard

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 (this is just an MCV)?

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

Solution

  • Yes it is possible. You can use unlabeled break statements inside loops, but not inside an 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")
    }