Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

Separating multiple if conditions with commas in Swift

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...