【问题标题】:method in protocol extension gets called instead of method implementation in View Controller调用协议扩展中的方法而不是视图控制器中的方法实现
【发布时间】:2018-06-01 07:40:11
【问题描述】:

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

并且那个 viewController 类符合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 ")
    }

}

【问题讨论】:

    标签: ios swift protocols swift-protocols protocol-extension


    【解决方案1】:

    这就是扩展中的方法的工作方式。他们将实现隐藏在一个类中。

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

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

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

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

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

    delegate.optionalMethod?()
    

    【讨论】:

    • 我一直在阅读这些 swift hacks hackingwithswift.com/example-code/language/…,我认为它们是相同的......所以没有。
    • @Ian 我刚刚意识到您忘记将可选方法放在协议定义本身中。你需要这样做。查看编辑。
    • 对了,我要回去再看一下协议扩展文档:(感谢帮助
    猜你喜欢
    • 2017-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多