3

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"
JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
Boon
  • 40,656
  • 60
  • 209
  • 315

1 Answers1

8

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
Community
  • 1
  • 1
Ian
  • 12,538
  • 5
  • 43
  • 62