斯威夫特:守卫让vs如果让 [英] Swift: guard let vs if let
问题描述
我一直在阅读有关Swift中的Optional的内容,并且看到了一些示例,其中使用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
的其他"情况必须退出当前范围.通常,这意味着它必须调用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
嵌套其作用域,不需要任何特殊的内容.它可以return
或不可以.
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.
这篇关于斯威夫特:守卫让vs如果让的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!