RMeeuws
RMeeuws

Reputation: 31

Swift delegate & optional

I've declared this protocol

protocol ReactorDelegate {
  func ReactorUpdateUI()
}

In my Model I have a delegate optional property and checking if isn't nill, unwrap it to call the protocol methode provided by the VC.

var delegate:ReactorDelegate? 

if delegate {delegate?.ReactorUpdateUI()}

My VC follows the protocol and has the ReactorUpdateUI methode

class VC_Reactor: UIViewController, ReactorDelegate

I'm trying to create an instance of the Model in the VC but this fails

let reactorCore=Reactor()

ERROR: 'Reactor' is not constructible with '()' what let's me know that not all properties have an initial value.

I can work-around it by making my delegate in the VC an implicitly unwrapped optional var reactorCore:Reactor! and in the ViewDidLoad with a custom init: reactorCore=Reactor(delegate:self)

I don't understand why I need a custom init(delegate:ReactorDelegate) if I declare the delegate property optional.

Upvotes: 3

Views: 7571

Answers (2)

NikLoy
NikLoy

Reputation: 448

You have to declare your protocol like this:

protocol ReactorDelegate: class {
   func ReactorUpdateUI()
}

And after, your delegate:

weak var delegate: ReactorDelegate
delegate?.ReactorUpdateUI()

Upvotes: 0

Nate Cook
Nate Cook

Reputation: 93276

You need to mark the method as optional in your delegate protocol:

@objc protocol ReactorDelegate {
    optional func ReactorUpdateUI()
}

Then mark your class as @objc and use optional chaining on the method, too:

delegate?.ReactorUpdateUI?()

Note: When writing a protocol, it's easiest to keep everything required and stub out the methods in your class, then when everything works go back and make what you want optional be optional. The error messages you get are pretty opaque, so this way you're working with fewer issues at a time.

Upvotes: 18

Related Questions