Boon
Boon

Reputation: 41480

Why does guard let x = x exhibit different scope behavior?

Why does guard let x = x inside a method behave differently than outside?

Example code below is copied right out of Playground.

var x:Int? = 3

func foo(x: Int?) {
    guard let x = x else {
        return
    }

     print(x)  // print "3\n"
}

foo(x)

guard let x = x else { 
  throw NSError(domain: "app", code: 0, userInfo: nil)
}

print(x)  // print "Optional(x)\n"

Upvotes: 3

Views: 1118

Answers (1)

Ian
Ian

Reputation: 12768

guard statements require a return,break,continue or throw in their else clause. If you correct the optional in x?.description the compiler will point out this error. Using guard outside of the scope of a function makes no sense because it is meant to check for a condition and break out of that scope if it invalid. You will get the error:

guard body may not fall through.

The only way for it to be valid in a playground (or outside the scope of a function) is to throw an error.

According to the documentation:

The else clause of a guard statement is required, and must either call a function marked with the noreturn attribute or transfer program control outside the guard statement’s enclosing scope using one of the following statements:

  • return
  • break
  • continue
  • throw

Upvotes: 8

Related Questions