简体   繁体   中英

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 ?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM