如何在函数外部和内部退出 GUARD - Swift
How to exit GUARD outside and inside a function - Swift
下面的代码我在练习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
语句在循环中,你也可以使用break
或continue
.
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
}
}
Or is GUARD only used within functions?
不一定。
If that condition is not met, the code inside the else
branch is executed. That branch must transfer control to exit the code block in which the guard
statement appears. It can do this with a control transfer statement such as return
, break
, continue
, or throw
, or it can call a function or method that doesn’t return, such as fatalError(_:file:line:)
.
例如,这可以用于顶层的 Playgound
for i in 0...10 {
guard i % 2 == 0 else { continue }
print(i)
}
错误信息实际上与guard
无关。它只是说明 return
不能在函数 之外使用
下面的代码我在练习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
语句在循环中,你也可以使用break
或continue
.
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
}
}
Or is GUARD only used within functions?
不一定。
If that condition is not met, the code inside the
else
branch is executed. That branch must transfer control to exit the code block in which theguard
statement appears. It can do this with a control transfer statement such asreturn
,break
,continue
, orthrow
, or it can call a function or method that doesn’t return, such asfatalError(_:file:line:)
.
例如,这可以用于顶层的 Playgound
for i in 0...10 {
guard i % 2 == 0 else { continue }
print(i)
}
错误信息实际上与guard
无关。它只是说明 return
不能在函数 之外使用