I'm struggling to understand how the new type Result of Swift works. Here is what I have tried:
enum MyError: Error {
case test
}
typealias MyResult = Result<Data?, MyError?>
I'm getting this error:
Type 'MyError?' does not conform to protocol 'Error'
Why is this happening? Thank you for your help.
It's because of the Result's signature:
public enum Result<Success, Failure> where Failure : Error
It doesn't accept an optional Error.
typealias MyResult = Result<Data?, MyError>
would work.
The introduction of the Result type is discussed in SE-235: Add Result to the Standard Library. One of the reasons was to provide a better solution compared to APIs like
func dataTask(with url: URL, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask
using both optional success values (Data?, URLResponse?) and optional errors (Errors?). The Swift language cannot express that either both data and response are non-nil or error is non-nil.
This leads to code which tests for “impossible” combinations, or uses forced-unwrapping (relying on the API documentation).
The Result type solves this problem by using an enumeration with associated values:
public enum Result<Success, Failure> where Failure : Error {
/// A success, storing a `Success` value.
case success(Success)
/// A failure, storing a `Failure` value.
case failure(Failure)
}
so that it unambiguously represents either success or failure. The Success type need not be an optional anymore, and the Failure type must be a non-optional error:
enum MyError: Error {
case test
}
typealias MyResult = Result<Data, MyError>
Example:
let resultOK = MyResult.success(Data())
let resultFailed = MyResult.failure(.test)
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