Delegates in swift?

前端 未结 12 1510
天命终不由人
天命终不由人 2020-11-22 03:27

How does one go about making a delegate, i.e. NSUserNotificationCenterDelegate in swift?

12条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 04:15

    I got few corrections to post of @MakeAppPie

    First at all when you are creating delegate protocol it should conform to Class protocol. Like in example below.

    protocol ProtocolDelegate: class {
        func myMethod(controller:ViewController, text:String)
    }
    

    Second, your delegate should be weak to avoid retain cycle.

    class ViewController: UIViewController {
        weak var delegate: ProtocolDelegate?
    }
    

    Last, you're safe because your protocol is an optional value. That means its "nil" message will be not send to this property. It's similar to conditional statement with respondToselector in objC but here you have everything in one line:

    if ([self.delegate respondsToSelector:@selector(myMethod:text:)]) {
        [self.delegate myMethod:self text:@"you Text"];
    }
    

    Above you have an obj-C example and below you have Swift example of how it looks.

    delegate?.myMethod(self, text:"your Text")
    

提交回复
热议问题