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

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

问题描述

看一个 Swift 示例:

Looking at a Swift example:

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

文档说明:

... 代码将该视图控制器分配给本地常量 sourceViewController,并检查是否有膳食属性在 sourceViewController 上为零.

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

问题:当用逗号分隔时,Swift 是否允许您在 if 语句中有多个条件(如本示例中 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.

因此,只有当一个值正确分配给 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天全站免登陆