Continue only allowed inside a loop?

I am trying to practice using guard statements, but I keep getting an error message in XCode, which says: "'continue' is only allowed inside a loop."

Could someone please let me know why I am getting this message? I don't understand what is wrong with my code. Thank you.

func calculateFibisAge() {
var fibisAge = 0
let fibisHair = "White"

if fibisAge != 100 && fibisHair != "Pink" {
guard fibisAge != 35 else {print("Fibi is now an adult")}

fibisAge += 1


What do you want the program to do at continue?

I'd like for it to check again for Fibi's age (that it's not equal to 35) and then keep adding 1 to Fibi's age.

To go back at the guard’s first expression? In that case, you’re repeating a portion of code, and need a “loop”.

while fibisAge == 35 {
  print("Fibi is now an adult")}
  fibisAge += 1

Though I couldn’t understand what your code as a whole is trying to do, so I’m not sure that’s what you want.

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”.
1 Like

Okay, I understand now, thank you Lantua! I see where I went wrong as well. Thank you!

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.

Terms of Service

Privacy Policy

Cookie Policy