在Swift中用逗号分隔多个if条件 [英] Separating multiple if conditions with commas in Swift
问题描述
我们已经知道 多个可选绑定可以在一个 if 中使用/guard 语句用逗号分隔它们,但不用 &&
例如
We already know multiple optional bindings can be used in a single if/guard statement by separating them with commas, but not with &&
e.g.
// Works as expected
if let a = someOpt, b = someOtherOpt {
}
// Crashes
if let a = someOpt && b = someOtherOpt {
}
玩弄游乐场,逗号样式的格式似乎也适用于布尔条件,尽管我在任何地方都找不到提及的内容.例如
Playing around with playgrounds, the comma-style format also seems to work for boolean conditions though I can't find this mentioned anywhere. e.g.
if 1 == 1, 2 == 2 {
}
// Seems to be the same as
if 1 == 1 && 2 == 2 {
}
这是用于评估多个布尔条件的公认方法吗?,
的行为是否与 &&
的行为相同,或者它们在技术上是否不同?>
Is this an accepted method for evaluating multiple boolean conditions, and is the behaviour of ,
identical to that of &&
or are they technically different?
推荐答案
其实结果不太一样.假设您在 if 和 && 中有 2 个语句.它们之间.如果在第一个语句中您使用可选绑定创建了一个 let ,那么您将无法在第二个语句中看到它.相反,您将使用逗号.
Actually the result is not the same. Say that you have 2 statements in an if and && between them. If in the first one you create a let using optional binding, you won't be able to see it in the second statement. Instead, using a comma, you will.
逗号示例:
if let cell = tableView.cellForRow(at: IndexPath(row: n, section: 0)), cell.isSelected {
//Everything ok
}
&&示例:
&& Example:
if let cell = tableView.cellForRow(at: IndexPath(row: n, section: 0)) && cell.isSelected {
//ERROR: Use of unresolved identifier 'cell'
}
希望这会有所帮助.
这篇关于在Swift中用逗号分隔多个if条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!