美文网首页
Swift protocol

Swift protocol

作者: 奋斗的蝼蚁 | 来源:发表于2017-06-20 23:25 被阅读0次

    @objc protocol MyClassDelegate {

    func method()

    }

    或者

    protocol MyClassDelegate: class {

    func method()

    }

    protocol为什么要加 @objc 或者继承  :class

    这是因为 Swift 的 protocol 是可以被除了 class 以外的其他类型遵守的,而对于像 struct 或是 enum 这样的类型,本身就不通过引用计数来管理内存,所以也不可能用 weak 这样的 ARC 的概念来进行修饰。

    想要在 Swift 中使用 weak delegate,我们就需要将 protocol 限制在 class 内。一种做法是将 protocol 声明为 Objective-C 的,这可以通过在 protocol 前面加上 @objc 关键字来达到,Objective-C 的 protocol 都只有类能实现,因此使用 weak 来修饰就合理了

    相关文章

      网友评论

          本文标题:Swift protocol

          本文链接:https://www.haomeiwen.com/subject/lczaqxtx.html