【发布时间】:2014-07-23 00:13:54
【问题描述】:
我在为一个对象分配委托时遇到问题,该对象是一个在 Swift 中定义协议的类的实例,如下所示:
我将代码简化为最简单的例子来说明问题: 这是带有协议的类
protocol TheProtocol {
func notifyDelegate()
}
class ClassWithProtocol: NSObject {
var delegate: TheProtocol?
fire() {
delegate?.notifyDelegate()
}
}
这是符合协议的类
class ClassConformingToProtocol: NSObject, TheProtocol {
var object: ClassWithProtocol?
func notifyDelegate() {
println("OK")
}
init() {
object = ClassWithProtocol()
object?.delegate = self // Compiler error - Cannot assign to the result of this expression
object?.fire()
}
}
我尝试了各种替代方法来分配委托,但均未成功。知道我缺少什么吗?
【问题讨论】:
标签: ios delegates swift protocols