Home > Back-end >  Why can we use Error protocol as generic type?
Why can we use Error protocol as generic type?

Time:11-26

Why is it possible for Error protocol? For any other protocol, we receive error

protocol SomeProtocol {

}

struct Test1<T> where T: SomeProtocol {

}

struct Test2<T> where T: Error {

}

let test1: Test1<SomeProtocol> = Test1() ----> Protocol 'SomeProtocol' as a type cannot conform to the protocol itself
let test2: Test2<Error> = Test2() ----> It's Ok

CodePudding user response:

This is just an exception in the rule. It is documented here:

Exceptions

When used as a type, the Swift protocol Error conforms to itself; @objc protocols with no static requirements can also be used as types that conform to themselves.

If it weren't for this exception, you wouldn't be able to do Result<T, Error> or AnyPublisher<T, Error> to say "some result that can be any error" or "a publisher that can emit any error".

  • Related