为什么不调用iOS中的自定义委托

LC *_*C 웃 2 delegates ios swift swift-playground

我正在尝试使用swift中的playground创建自定义委托.但是,不通过回调调用doSomething方法.似乎委托?.doSomething()不会触发XYZdoSomething方法.提前致谢!

import UIKit

@objc protocol RequestDelegate
{
    func doSomething();

      optional  func requestPrinting(item : String,id : Int)
}


class ABC
{
    var delegate : RequestDelegate?
     func executerequest() {

        delegate?.doSomething()
        println("ok delegate method will be calling")
    }
}   

class XYZ : RequestDelegate
{  
    init()
    {
        var a  = ABC()
        a.delegate = self
    }

     func doSomething() {
       println("this is the protocol method")
    }
}    

var a = ABC()
a.executerequest()
Run Code Online (Sandbox Code Playgroud)

Mar*_*n R 7

似乎delegate?.doSomething()不会触发XYZ类 doSomething方法.

那是正确的.class ABC有一个可选delegate属性,但属性的值没有设置.所以delegatenil ,因此是可选的链接

delegate?.doSomething()
Run Code Online (Sandbox Code Playgroud)

什么都不做.您还定义了一个class XYZ但未创建该类的任何实例.

如果将委托设置为a实例,XYZ则它将按预期工作:

var a = ABC()
a.delegate = XYZ()
a.executerequest()
Run Code Online (Sandbox Code Playgroud)