Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift generics postponed issue

I'm trying to do this but I'm getting some troubles

This is CustomProtocol

protocol CustomProtocol {

}

SubCustomProtocol

protocol SubCustomProtocol: CustomProtocol {

}

SubCustomProtocolImplementation

class SubCustomProtocolImplementation: SubCustomProtocol {

}

This is CustomClass

class CustomClass<P: CustomProtocol> {

    var customProtocol: P?

    func doSomething() {

    } 

}

SubCustomClass

class SubCustomClass<P: SubCustomProtocol>: CustomSubClass {

}

And my BaseViewController

class BaseViewController<P: CustomProtocol, T: CustomClass<P>>: UIViewController {

    var foo: T!

    override func viewDidLoad() {
        super.viewDidLoad()
        foo?.doSomething()
    }
}

My ViewController

class ViewController<P: SubCustomProtocolImplementation, T: SubCustomClass<P>>: BaseViewController<P,T> {

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

In the line where I call foo?.doSomething() it says that 'T' is not a subtype of 'CustomClass<'P'>' and I don't know what I'm doing wrong

And in the ViewController declaration it says that "BaseViewController requires that T inherit from CustomClass<'P'>"

Hope you can help me!

like image 428
Roberto Frontado Avatar asked Feb 12 '16 08:02

Roberto Frontado


1 Answers

If you want to specify your foo var type as CustomClass<P> you should do as following instead.

class ViewController<P: CustomProtocol>: UIViewController {

    var foo: CustomClass<P>?

    override func viewDidLoad() {
        super.viewDidLoad()
        foo?.doSomething()
    }
}
like image 128
iyuna Avatar answered Oct 06 '22 16:10

iyuna