This question already has answers here:
If the Swift 'guard' statement must exit scope, what is the definition of scope?

(3个答案)


3年前关闭。




在下面的代码中,我正在练习GUARD的使用(书:OReilly Learning Swift)
guard 2+2 == 4 else {
print("The universe makes no sense")
return // this is mandatory!
}
print("We can continue with our daily lives")

为什么会出现以下代码错误?
error: return invalid outside of a func
还是仅在功能内使用GUARD?

最佳答案

如果不满足guard语句中的条件,则else分支必须退出当前作用域。如错误消息所示,return只能在函数内部使用,但是return不是退出范围的唯一方法。

您也可以在函数外部使用throw,如果guard语句处于循环中,则还可以使用breakcontinue
return在函数中有效:

func testGuard(){
    guard 2+2 == 4 else {
        print("The universe makes no sense")
        return // this is mandatory!
    }
    print("We can continue with our daily lives")
}
throw在函数外部也有效:
guard 2+2 == 4 else { throw NSError() }
break在循环中有效:
for i in 1..<5 {
    guard i < 5 else {
        break
    }
}

关于swift - 如何在函数的内部和外部退出GUARD-Swift,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47638413/

10-13 03:49