Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type 'MyError?' does not conform to protocol 'Error'

Tags:

swift

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.

like image 275
Another Dude Avatar asked Jul 12 '26 02:07

Another Dude


2 Answers

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.

like image 50
EDUsta Avatar answered Jul 13 '26 16:07

EDUsta


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)
like image 34
Martin R Avatar answered Jul 13 '26 15:07

Martin R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!