iosswiftprotocolsswift-protocolsprotocol-extension

method in protocol extension gets called instead of method implementation in View Controller


so I have a viewController which holds a custom view,

and that viewController class conforms to ViewProtocol

I expect when someAction method triggered in someCustomizedView

it will print " method in otherCustomizedClass called "

but it prints (" method in extension Called") instead.

The theNotOptionalMethod works just fine but not the optional method.

Is there anything that I misunderstand of protocol extension ?

Please help, been struggling for hours, thanks

protocol ViewDelegate: class {

    func theNOTOptionalMethod()

}

extension ViewDelegate {

    func theOptionalMethod(){
        print (" method in extension Called")
    }
}

class someCustomizedView: UIView {

    weak var deleage: ViewDelegate?

    @IBAction func someAction(sender: UIButton) {
        deleage?.theOptionalMethod()
    }
}

class someCustomizedVC: UIViewController, ViewDelegate {

    lazy var someView: someCustomizedView = {
        var v = someCustomizedView()
        v.deleage = self
        return v
    }()


    //...... someView added to controller


    func theNOTOptionalMethod() {
        // do nothing
    }

    func theOptionalMethod() {
        print (" method in otherCustomizedClass called ")
    }

}

Solution

  • That is how methods in extensions work. They hide the implementations in a class.

    To create a protocol with optional methods, you need to put the optional method in the protocol definition:

    protocol ViewDelegate: class {
    
        func theNOTOptionalMethod()
        func theOptionalMethod()
    
    }
    

    Alternatively, you can use @objc and optional modifiers:

    @objc protocol MyDelegate : class{
        func notOptionalMethod()
        @objc optional func optionalMethod()
    }
    

    When you call optionalMethod, you need to unwrap the optional:

    delegate.optionalMethod?()