Arnie Schwarzvogel
Arnie Schwarzvogel

Reputation: 1005

Could not cast value of type - initialising with protocol (Swift)

I'm implementing simple MVP pattern for View Controller in Swift (3).

View is defined like a protocol:

protocol WirelessSpeakersView {

    func present()
    func goBack()
    func alertSaveFailed()
}

And I'm constructing the presenter in the ViewController like this:

class WirelessSpeakersViewController: UIViewController, WirelessSpeakersView  {

    private let presenter: WirelessSpeakersPresenter = WirelessSpeakersPresenter(view: self as! WirelessSpeakersView)

But the last line produces run time exception

Could not cast value of type '(WirelessSpeakersViewController) -> () -> WirelessSpeakersViewController' (0x102cfbf20) to 'WirelessSpeakersView' (0x102cfbf58).

which I do not get. Why the type naming looks so complex (-> () -> ) ? I do not expect any difficulties cause the ViewController properly implements View protocol.

Upvotes: 0

Views: 626

Answers (1)

Siju
Siju

Reputation: 510

Make variable presenter lazy or initialize it after viewcontroller initialization. This error might be because its trying to type cast viewcontroller object before getting initalized.

private lazy var presenter: WirelessSpeakersPresenter = {
        let p = WirelessSpeakersPresenter(view: self as! WirelessSpeakersView)
        return p
    }()

Upvotes: 4

Related Questions