Swift 3 generic extension constraint with generic parameter

Viewed 2049

Here is what I want to achieve:

I have a generic struct struct Future<Element> {} and another generic struct Response<T> {}. I want to write a method that is in extension for Future that is only valid when Element is Response<T>. It doesn't matter what T is. So here is the code:

extension Future where Element == Response { }

But swift compiler complains that Reference to generic type 'Response' requires arguments in <...>. Is there another way to achieve this in swift?

2 Answers

I know it's been a while since you asked, but I was trying to solve a similar problem just now... What about writing the extension this way, as a generic function with the constraints you want?

struct Future<Element> {
    let elem: Element
}
struct Response<T> {
    let t: T
}

extension Future {
    func newFunc<X>() where Element == Response<X> {
        print("My Element is a Response: \(elem.t)")
    }
}
Related