【问题标题】:Swift if statement - multiple conditions separated by commas?Swift if 语句 - 多个条件用逗号分隔?
【发布时间】:2016-02-16 14:18:28
【问题描述】:

看着 Swift example:

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

文档指出:

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

问题:Swift 是否允许您在 if 语句中使用逗号分隔多个条件(如本例中 MealViewController 之后的逗号)?

在文档中没有看到这个。

【问题讨论】:

  • 在可选绑定的情况下是的,其余的使用正常的if语法来混合条件

标签: ios swift if-statement optional


【解决方案1】:

当你写的时候是的

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

}

只有当所有任务都正确完成时,Swift 才会执行IF 的主体。

更多

这种技术的另一个特点:分配是按顺序完成的。

所以只有当一个值被正确地分配给a,Swift 才会尝试给b 分配一个值。以此类推。

这允许您像这样使用先前定义的变量/常量

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

}

在这种情况下(在第二次赋值中),我们可以安全地使用a,因为我们知道如果执行了该代码,那么a 已经被填充了一个有效值。

【讨论】:

    【解决方案2】:

    是的。 Swift: Documentation: Language Guide: The Basics: Optional Binding 说:

    您可以根据需要在单个if 语句中包含任意数量的可选绑定和布尔条件,以逗号分隔。如果可选绑定中的任何值是nil 或任何布尔条件计算为false,则整个if 语句的条件被认为是false。以下if 语句是等效的:

    if let firstNumber = Int("4"), let secondNumber = Int("42"), firstNumber < secondNumber && secondNumber < 100 {
        print("\(firstNumber) < \(secondNumber) < 100")
    }   
    // Prints "4 < 42 < 100"
    
    if let firstNumber = Int("4") {
        if let secondNumber = Int("42") {
            if firstNumber < secondNumber && secondNumber < 100 {
                print("\(firstNumber) < \(secondNumber) < 100")
            }   
        }   
    }   
    // Prints "4 < 42 < 100"
    

    【讨论】:

    • 我自己从不知道 where 子句,直到在文档中查找它,你每天都会学到新东西...... :)
    • where clauses are no longer used like that in Swift 3,只需将where 替换为逗号即可。
    • 仅供参考,if 语句中的 where 子句在 Swift 4+ 中不再有效。我相信它在 Swift 3 中已被删除,但我找不到参考)
    • 使用逗号和使用 && 一样吗? if let a = optA && let b = optB && let c = optC {
    • @mretondo,至少在 Swift 4.1 中,您的示例给出了错误 Expected ','joining parts of a multi-clause condition,以及修复的建议将&amp;&amp; 替换为,。使用逗号是一种确保您没有可选项的方法,而使用 &amp;&amp; 表示布尔测试。要使用&amp;&amp;,您必须改为:if optA != nil &amp;&amp; optB != nil &amp;&amp; optC != nil {。或者,如果您需要块内的那些未包装变量,您可以再次使用逗号:if let a = optA, a&gt;1, let b = optB, b&gt;1, let c = optC, c&gt;1 { return a + b + c }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-11
    • 2017-11-15
    • 2013-12-17
    • 1970-01-01
    • 2015-10-13
    • 1970-01-01
    相关资源
    最近更新 更多