How to accomplish a weak delegate,and the protocol in swift How to inherit ?- 2018-01-11

How to accomplish a weak delegate,and the protocol in swift How to inherit ?
  • The way to accomplish a weak delegate,and that protocol‘s inheritance in swift ?

  • A smaple:

      protocol ProtocolNameDelegate {
          // Protocol stuff goes here
      }
      
      class SomeClass {
          weak var delegate: ProtocolNameDelegate? \\ error occured
      }           
    
    • error:

      • 当你在swift中为代理设置weak属性以便于避免循环引用的时候,报编译错误

          'weak' may only be applied to class and class-bound protocol types, not 'MyImageCellDelegate'
        
    • Why did this error occur?

      • 因为在swift中协议是不仅可以被引用类型实现,也可以被值类型引用,但是weak只能用来修饰引用类型,所以在使用weak修饰没有加任何限定词的协议时报错,我们将如何使用weak修饰协议定义的类型属性呢
        • 有如下三种方法:

            protocol ProtocolNameDelegate: class {
                // Protocol stuff goes here
            }
            
            or
            
            protocol ProtocolNameDelegate: NSObjectProtocol {
                // Protocol stuff goes here
            }
            
            or
            
            @objc protocol ProtocolNameDelegate {
                // Protocol stuff goes here
            }
            
            Although, under code is successed to build, but which one is the best?
            
            class SomeClass {
                weak var delegate: ProtocolNameDelegate?
            }
          
        • which one is the best way to use the weak keywords with Protocol Type Parameter ?

          • NSObjectProtocol is equal to NSObject Protrocol in Objective-C
          • @objc keyword is define the type as objective-c types
          • class keyword limit the protocol only used for reference type in swift

          All in all , NSObjectProtocol > class > @objc

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,181评论 0 10
  • The Inner Game of Tennis W Timothy Gallwey Jonathan Cape ...
    网事_79a3阅读 14,308评论 3 20
  • 立在鸡群同齐哢,生自农家食俗谷。 万里雄心厌玉笼,不恋人间鲜肥物。 举世局疮未痊愈,丹志不酬难纵歌。 扶摇还需好仙...
    东方惠阅读 3,051评论 2 6
  • 江湖传说,有一只猫,力大无穷却身轻如燕(。・ω・。);有一只猫,行侠仗义却不留名号╭(╯^╰)╮;有一只猫,无人知...
    猫猫阳阅读 3,401评论 0 0
  • 这篇文章太好了,太感人了,太启迪人了!我非常赞赏! 善良无需考证 巴西著名导演沃尔特·塞勒斯正在...
    甜笑笑感恩有您阅读 1,670评论 0 1

友情链接更多精彩内容