我正在尝试使用swift中的playground创建自定义委托。但是, doSomething 方法未通过回调调用。 似乎 委托?.doSomething() 不会触发 XYZ 类 doSomething 方法。 提前致谢!
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()
答案 0 :(得分:7)
delegate?.doSomething()
似乎没有激发到XYZ类doSomething
方法。
这是正确的。 class ABC
具有可选的delegate
属性,但值为。{
该物业无处可寻。所以delegate
是nil
因此可选链接
delegate?.doSomething()
什么都不做。你也定义了一个class XYZ
但是
没有创建该类的任何实例。
如果您将a
的委托设置为XYZ
的实例,那么
它将按预期工作:
var a = ABC()
a.delegate = XYZ()
a.executerequest()