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 }
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 { ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With