Jason
Jason

Reputation: 1067

Protocols and delegate trouble in swift

All,

I have create a swift file and put a protocol in it, like this :

protocol PayButtonProtocol {
    func enablePayButton()
    func disablePayButton()
}

I have made my viewcontroller conform to the protocol like this :

class ViewController: UIViewController, PayButtonProtocol

I have also created the functions in the ViewController so it conforms like this

func enablePayButton() {
        println("Button enabled")
        PAYBarButton.enabled = true
    }

    func disablePayButton() {
        PAYBarButton.enabled = false
    }

And in another class, I have set the delegate and I want to execute the enablePayButton when something is pressed like this :

 var delegate:PayButtonProtocol?

and in the function i want to execute one of the functions by :

delegate?.enablePayButton()

but it doesn't execute, what am I missing please ?

Upvotes: 0

Views: 48

Answers (1)

Duncan C
Duncan C

Reputation: 131491

More than likely delegate is nil. Add a breakpoint and check the value of delegate before that line executes. Or change the "?" to a "!" and it will crash if delegate is nil, letting you know what's wrong.

Your code in the other class:

var delegate:PayButtonProtocol?

defines a variable named delegate that is of type PayButtonProtocol?.

The variable delegate will contain nil until you assign something to it:

delegate = <someObjectThatConformsToPayButtonProtocol>

Upvotes: 1

Related Questions