Separating multiple if conditions with commas in Swift

后端 未结 6 1528
轮回少年
轮回少年 2020-11-30 13:56

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.



        
6条回答
  •  遥遥无期
    2020-11-30 14:20

    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.

    Comma example:

    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'              
    }
    

    Hope this helps.

提交回复
热议问题