swift - 在 Swift 中用逗号分隔多个 if 条件

标签 swift

我们已经知道multiple optional bindings can be used in a single if/guard statement by separating them with commas , 但不是 && 例如

// Works as expected
if let a = someOpt, b = someOtherOpt {
}
// Crashes
if let a = someOpt && b = someOtherOpt {
}

玩 Playground ,逗号格式似乎也适用于 bool 条件,尽管我在任何地方都找不到这个。例如

if 1 == 1, 2 == 2 {
}
// Seems to be the same as
if 1 == 1 && 2 == 2 {
}

这是评估多个 bool 条件的公认方法吗? 的行为是否与 && 的行为相同,或者它们在技术上是否不同?

最佳答案

其实结果不一样。假设您在 if 和 && 之间有 2 个语句。如果在第一个语句中您使用可选绑定(bind)创建了一个 let,您将无法在第二个语句中看到它。相反,您将使用逗号。

逗号示例:

if let cell = tableView.cellForRow(at: IndexPath(row: n, section: 0)), cell.isSelected {
    //Everything ok
}

&& 示例:

if let cell = tableView.cellForRow(at: IndexPath(row: n, section: 0)) && cell.isSelected {
    //ERROR: Use of unresolved identifier 'cell'              
}

希望这对您有所帮助。

关于swift - 在 Swift 中用逗号分隔多个 if 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46262786/

相关文章:

ios - 可视化点击 View ,显示点击指示器

swift - 我如何快速设置 MPVolumeView?

swift - 动画时如何以编程方式禁用约束

multithreading - NSSplitViewItem 折叠动画和窗口 setFrame 冲突

swift - 之间的区别?和 !在 Swift 语言中?

ios - UIButton 单击导致应用程序卡住/内存快速增加

ios - 设置 SKTileMapNode 颜色时出现问题

ios - 有没有等同于 Swift/Obj-C/iOS 的 ruby​​ 控制台?

ios - UISegmentedControl TintColor 到渐变色

swift - UIView.animate - 将 .autoreverse 与其他选项一起使用