Reputation: 2748
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 {
}
Upvotes: 2
Views: 1008
Reputation: 2748
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
}
make sure writing Element: Resultable
not Element == Resultable
. This was the reason my code wasn't working in the first place.
Upvotes: 2