LC *_*C 웃 2 delegates ios swift swift-playground
我正在尝试使用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()
Run Code Online (Sandbox Code Playgroud)
似乎
delegate?.doSomething()不会触发XYZ类doSomething方法.
那是正确的.class ABC有一个可选delegate属性,但属性的值没有设置.所以delegate是nil
,因此是可选的链接
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)
| 归档时间: |
|
| 查看次数: |
3679 次 |
| 最近记录: |