斯威夫特:守卫让与如果让 [英] Swift: guard let vs if let
问题描述
我一直在阅读有关 Swift 中的 Optionals 的内容,并且我看到了一些示例,其中 if let
用于检查 Optional 是否包含一个值,如果确实如此 - 对解包的值执行一些操作.
I have been reading about Optionals in Swift, and I have seen examples where if let
is used to check if an Optional holds a value, and in case it does – do something with the unwrapped value.
然而,我已经看到在 Swift 2.0 中,关键字 guard let
被主要使用.我想知道 if let
是否已从 Swift 2.0 中删除,或者是否仍然可以使用.
However, I have seen that in Swift 2.0 the keyword guard let
is used mostly. I wonder whether if let
has been removed from Swift 2.0 or if it still possible to be used.
我应该将包含 if let
的程序更改为 guard let
吗?
Should I change my programs that contain if let
to guard let
?
推荐答案
if let
和 guard let
服务类似但不同的目的.
if let
and guard let
serve similar, but distinct purposes.
guard
的else"情况必须退出当前作用域.通常这意味着它必须调用 return
或中止程序.guard
用于提供提前返回,而无需嵌套函数的其余部分.
The "else" case of guard
must exit the current scope. Generally that means it must call return
or abort the program. guard
is used to provide early return without requiring nesting of the rest of the function.
if let
嵌套了它的作用域,不需要任何特殊的东西.它可以返回
,也可以不返回.
if let
nests its scope, and does not require anything special of it. It can return
or not.
一般来说,如果 if-let
块将成为函数的其余部分,或者它的 else
子句将有一个 return
或在其中中止,那么您应该使用 guard
代替.这通常意味着(至少根据我的经验),当有疑问时,guard
通常是更好的答案.但是在很多情况下 if let
仍然是合适的.
In general, if the if-let
block was going to be the rest of the function, or its else
clause would have a return
or abort in it, then you should be using guard
instead. This often means (at least in my experience), when in doubt, guard
is usually the better answer. But there are plenty of situations where if let
still is appropriate.
这篇关于斯威夫特:守卫让与如果让的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!