Desmond
Desmond

Reputation: 787

Is checking nil and empty for a set at the same time safe in Swift?

I just want to check whether a set is empty or nil, so I wonder whether the code below is safe or not. (Would it be passible if the newValue is nil and the system runs (newValue!).count and causes an error?)

if newValue == nil ||  (newValue!).count == 0{
    // Actions here        
}

Upvotes: 2

Views: 581

Answers (3)

Lucas van Dongen
Lucas van Dongen

Reputation: 9858

It is perfectly safe as it will execute the second statement only when the first one is true.

It's better to use:

   guard let newValue = newValue // First unwrap it
       where newValue.count > 0 else { // Then check if the unwrapped value has items
           return // If not we don't continue
   }

   // From this point you don't need to use ? or ! to access newValue anymore 

Always try to use safe patterns in your Swift code. To me casting with ! is a code smell and I would always try to replace it with a if let thing = thing or guard let thing = thing statement

Upvotes: 3

Julian
Julian

Reputation: 9337

In this case it is safe. Because first part makes the whole statement true so there is no need to evaluate the second part.

If it is possible to determine the result of the whole condition after its part then rest is not evaluated. This is one of the reasons why conditions shouldn't have any side effects (mutate anything)

For a bit more general reading

Upvotes: 1

luk2302
luk2302

Reputation: 57124

That statement is perfectly fine and save.

The correct term for this kind of behavior of programming languages is short-circuit evaluation.

The boolean statements are only executed until the statement can possibly still result in both true and false - as soon as the outcome is determined it finishes.

For && that means that if one statement is false the execution stops.
For || that means that if one statement is true the execution stops.

Upvotes: 1

Related Questions