简体   繁体   中英

Extend a protocol with generic associatedtype

Let's say we have a protocol defined as:

protocol PAT {
    associatedtype Element
}

and I also have an enum(typical Result) defined as:

enum Result<Value> {
    case success(Value)
    case error(Error)
}

Now I want to add an extension to PAT when Element is Result<Value> but compiler can not determine Value hence triggers a compile error indicating "reference to generic requires argument".

here's the code for extension:

extension Pat where Element == Result {
}

The solution is to create another protocol with associatedType to wrap Result in it.

protocol Resultable {
    associatedType ValueType
    var isSuccess: Bool { get }
    var value: ValueType? { get }
}

and make Result extend Resultable:

extension Result: Resultable {
    typealias ValueType = Value
    var isSuccess: Bool { ... }
    var value: ValueType? { ... }
}

and extend PAT using Resultable :

extension PAT where Element: Resultable {
    // in here you have access to Resultable.ValueType
}

Note

make sure writing Element: Resultable not Element == Resultable . This was the reason my code wasn't working in the first place.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM