斯威夫特2:守卫体可能不会因误差而跌倒

jam*_*rez 28 swift2

我有以下警卫片,它产生的错误是"护卫体可能无法通过".怎么了?

 guard NSFileManager.defaultManager().fileExistsAtPath(appBundlePath) else {
        print("App bundle doesnt exist")
 }
Run Code Online (Sandbox Code Playgroud)

jam*_*rez 49

guard语句需要有一些东西可以使程序的流程远离封闭范围(例如,最有可能的情况是return从函数返回).这是必需的,因为守卫守卫的条件无效,所以程序流程需要去其他地方!

文件:

guard语句的else子句是必需的,并且必须使用以下语句之一调用标记有noreturn属性的函数或将程序控制转移到guard语句的封闭范围之外:

  • 返回
  • 打破
  • 继续


Riz*_*oob 5

这是上面答案中解释的示例,以使其更清楚。

在更外部的程序范围内保护语句。

guard false else {
    print("Condition is not true ")
}
print("Condition met")
Run Code Online (Sandbox Code Playgroud)

此代码 s 产生此错误语句

错误:如果guard statement.playground:1:1: error: 'guard' body may not fall through,考虑使用'return'或'throw'退出作用域

简单的错误消息意味着,您需要使用 return、break、continue 或 throw 语句从保护语句转移程序控制权。

带返回传输控制语句

guard false else {
    print("Condition is not true")
    return
}
print("Condition met")
Run Code Online (Sandbox Code Playgroud)

控制台输出

满足条件