Using a comma rather than && in an if statement

I noticed when filling in the updated text for the textField delegate (page 132 right before “More on protocols”) that instead of using an && for “and” in the if statement the two conditions are separated out by a comma.

Example:
if existingTextHasDecimalSeparator != nil,
replacementTextHasDecimalSeparator != nil {
return false
} else {
return true
}

Looking online at conditional statements I only found examples of Swift conditions using && or ||. Although, obviously, using a comma works the same I was just wondering if there’s a major difference between the two, when you may use one over the other, and if there’s an equivalent replacement for “or/||”?

When you’re just chaining together boolean conditions like that, I think the comma acts the same as &&. I don’t think there’s an equivalent replacement for ||.

The comma is mainly used for unwrapping optionals:

if let theError = errorCodeOptionalString,
   let errorInt = Int(theError),
   errorInt == 404 {
       ...

If you replaced the commas in that statement with &&, you’d get an error from Xcode complaining that theError was an unresolved identifier in the second line and the same complaint about errorInt in the third line. You have to use the comma separator to be able to reference the unwrapped optionals within the same if statement. The only other way you could write that would be to break them out into nested ifs:

if let theError = errorCodeOptionalString {
  if let errorInt = Int(theError) {
    if errorInt == 404 {
      ...

The comma separator lets you condense that down to a single if.

2 Likes