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"
guardstatements require areturn,break,continueorthrowin theirelseclause. If you correct the optional inx?.descriptionthe 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: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: