Thank you Lantua, is it possible to use a guard statement outside of the context of optionals? For example can I use a guard statement in an if statement?
Guard statement can be used anywhere. The problem in your code is continue.
continue will go to the next loop, so you need a loop to go to, hence the warning.
for a in array {
continue // go to the next `for` iteration.
}
guard is essentially a reverse if, so any where if is permitted, so will guard.
guard value else {
// We go in here ONLY if `value` is FALSE
}
The main difference is that you need to get out of the current scope, using `continue`, `break`, or `return`. This is because `guard` is designed to handle something that make “the code unable to go on”.
Be careful that you go into guard When the statement is false in contrast to if that goes in when the statement is true.
if statement {
// when statement is TRUE
} else {
// when statement is FALSE
}
// common for both `TRUE` and `FALSE`
guard statement else {
// when statement is FALSE
}
// when statement is TRUE
Note that there’s no “common” code for guard because guard forces you to bail out if you go into false case. This is perhaps also part of the design.