调用协议扩展中的方法而不是视图控制器中的方法实现

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

所以我有一个包含自定义视图的 viewController,

并且viewControllerclass符合ViewProtocol

我预计 someAction 方法会在 someCustomizedView

中触发

它将打印 " method in otherCustomizedClass called "

但它会打印 (" method in extension Called")

theNotOptionalMethod 工作正常但不是可选方法。

我对协议扩展有什么误解吗?

请帮忙,苦苦挣扎了几个小时,谢谢

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 ")
    }

}

扩展中的方法就是这样工作的。他们将实现隐藏在 class.

要创建带有可选方法的协议,您需要将可选方法放在协议定义中:

protocol ViewDelegate: class {

    func theNOTOptionalMethod()
    func theOptionalMethod()

}

或者,您可以使用 @objcoptional 修饰符:

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

当你调用optionalMethod时,你需要解包可选的:

delegate.optionalMethod?()