简体   繁体   中英

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        
}

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM