Reputation: 6965
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 }
Upvotes: 4
Views: 2966
Reputation: 2587
guard error == nil else {
print(error!)
return
}
You're safe to force unwrap error in the body since you know it's isn't a null pointer.
You're better off with
if let error = error {
//handle error
return
}
Upvotes: 4
Reputation: 285200
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 { ...
Upvotes: 9
Reputation: 539975
The documentation states that when the closure is called:
data
has a value and error
is nil
(if the request was successful), data
is nil
and error
has a value (if the request failed).What you are really interested in is the data, and in the success case you have to (somehow) unwrap that anyway.
Therefore I would check if data
has a value. If that fails, you have an error. To avoid forced unwrapping use the nil-coalescing operator:
session.dataTask(with: url) { (data, response, error) in
guard let data = data else {
// The request failed.
let message = error?.localizedDescription ?? "Unknown error"
// Present message ...
return
}
// The request was successful.
// Process data ...
}
Upvotes: 5