Swift 2: guard body may not fall through error

梦想与她 提交于 2019-12-18 12:46:18

问题


I have the following guard snippet, which is producing the error 'guard body may not fall through'. Whats wrong?

 guard NSFileManager.defaultManager().fileExistsAtPath(appBundlePath) else {
        print("App bundle doesnt exist")
 }

回答1:


The guard statement needs to have a something to take the flow of the program away from the enclosing scope (e.g. most likely case is return to return from the function). This is required as the condition that guard is guarding will not be valid, so the program flow needs to go elsewhere!

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



回答2:


Consider using a return statement

A return statement occurs in the body of a function or method definition and causes program execution to return to the calling function or method.




回答3:


Here is the Example of what explained in above answers to make it more clear.

guard statement in more outer scope of programme.

guard false else {
    print("Condition is not true ")
}
print("Condition met")

this code s produces this error statement

error: If guard statement.playground:1:1: error: 'guard' body may not fall through, consider using a 'return' or 'throw' to exit the scope

The error message in simple word means, you need to transfer program control from the guard statement using return, break, continue or throw statements.

with return transfer control statement

guard false else {
        print("Condition is not true")
        return
    }
    print("Condition met")

output in console

Condition met



来源:https://stackoverflow.com/questions/31138273/swift-2-guard-body-may-not-fall-through-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!