Swift if语句 - 用逗号分隔的多个条件? [英] Swift if statement - multiple conditions separated by commas?

查看:1004
本文介绍了Swift if语句 - 用逗号分隔的多个条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看Swift 示例

if let sourceViewController = sender.sourceViewController as? MealViewController, meal = sourceViewController.meal {
    ...
}

doc声明:


...代码将视图控制器分配给本地
常量sourceViewController,并检查是否sourceViewController上的meal属性
是nil。

... the code assigns that view controller to the local constant sourceViewController, and checks to see if the meal property on sourceViewController is nil.

问题:当你的if语句中,Swift让你有多个条件逗号(在此示例中使用逗号 MealViewController )?

Question: Does Swift let you have multiple conditions in your if statement when separated by commas (as in this example with the comma after MealViewController)?

在文档中没有看到这个。

Haven't seen this in the docs.

推荐答案

是当你写

if let a = optA, let b = optB, let c = optC {

}

Swift确实执行 IF 仅当所有作业都已正确完成

Swift does execute the body of the IF only if all the assignments are properly completed.

另一个此技术的功能:分配以顺序完成。

Another feature of this technique: the assignments are done in order.

因此,只有将值正确分配给<​​code> a ,Swift尝试将值赋给 b 。等等。

So only if a value is properly assigned to a, Swift tries to assign a value to b. And so on.

这允许你像这样使用之前定义的变量/常量

This allows you to use the previous defined variable/constant like this

if let a = optA, let b = a.optB {

}

在这种情况下(在第二次分配中)我们安全地使用 a ,因为我们知道如果执行该代码,然后 a 已填入有效值。

In this case (in second assignment) we are safely using a because we know that if that code is executed, then a has been populated with a valid value.

这篇关于Swift if语句 - 用逗号分隔的多个条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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