Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3 generic extension constraint with generic parameter

Tags:

generics

swift

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?

like image 652
mustafa Avatar asked Jul 13 '17 10:07

mustafa


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)")
    }
}
like image 75
Peter E Avatar answered Sep 26 '22 01:09

Peter E


One possible solution is creating a dummy protocol which Response would conform to:

protocol ResponseObject {}

struct Response<T> {}
extension Response: ResponseObject {}

Then you'll be able to check against protocol conformance in your extensions:

extension Future where Element: ResponseObject {
    // ...
}
like image 25
xoudini Avatar answered Sep 24 '22 01:09

xoudini