Why does the guard assume that x = x exhibits behavior in different areas?

Why does the defender let x = x behave differently inside the method than outside?

The example code below is copied directly from the 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"

      

+3


source to share


1 answer


Operators

guard

require < return

, break

, continue

or throw

in its offer else

. If you correct the option in x?.description

, the compiler will indicate this error. Using a guard outside the scope of the function doesn't make sense as it is designed to check the status and exit this scope if it is invalid. You will receive an error:

guard

the body cannot fail.

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



According to the documentation :

The else clause of the guard instruction is required and must either invoke the function marked with the noreturn attribute or the transfer control program outside the guard instructions covering the scope using one of the following statements:

  • return
  • break
  • proceed
  • throw
+8


source







All Articles