Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift reverse guard issues

Tags:

ios

swift

I have closure that may return an error. It look like:

session.dataTask(with: url) { (data, response, error) in

Next I want to handle error. I want to use guard statement for unwrap error, and if it exist, that show alert and return function. But how could I perform something like

guard !(let error = error) else { return }

I can't. I can check for nil and then unwrap error again, but that look kind of ugly. Or I can use if let unwrapping, but for error checking I prefer guard. So, is there any way to nicely write following?

guard !(let error = error) else { return }
like image 461
Evgeniy Kleban Avatar asked Dec 01 '22 10:12

Evgeniy Kleban


1 Answers

Don't fight the framework.

  • If you want to use the unwrapped optional within the braces use if let

    if let error = error {
       print(error)
       return
    }
    
  • If you want to use the unwrapped optional after the braces use guard let

    guard let error = error else {
       return
    }
    print(error)
    
  • If the (unwrapped) content of error doesn't matter just check for nil

    guard error == nil else { ... 
    if error == nil { ... 
    
like image 104
vadian Avatar answered Dec 05 '22 10:12

vadian