"'break' is only allowed inside a loop, if, do, or switch" error message inside guard statement is misleading

I think the problem is that do is basically structural — it introduces a nested scope, but that's about all it does.

Loop constructs also introduce a scope, but they're more than structural because that scope is (in general) executed multiple times. Unlabelled break from a loop can be thought of as terminating the loop, rather than exiting the scope. (For comparison, continue exits the scope, but it doesn't terminate the loop.)

Thus, it's going to be a bit problematic if you rearrange the code inside a loop, introducing a nested do block, and that changes the semantics of an unlabelled break within the code you're rearranging.

There's another reason, too. Anyone coming to Swift from C or Obj-C (a lot of people) has a predisposition to think that unlabelled break exits only loops, not other kinds of scopes. Such people might, with an unlabelled break inside a do inside a loop, make the wrong assumption about what it does, and it wouldn't necessarily be obvious to them that it's wrong.

(There are other cases where Swift has sacrificed — or might sacrifice — your personal convenience in favor of protecting the masses.)

1 Like