斯威夫特:守卫让vs如果让 [英] Swift: guard let vs if let

查看:96
本文介绍了斯威夫特:守卫让vs如果让的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读有关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 letguard 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆