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

你可能感兴趣的:(How to accomplish a weak delegate,and the protocol in swift How to inherit ?- 2018-01-11)