【问题标题】:Compiler error when assigning the Delegate for a Protocol in Swift iOS在 Swift iOS 中为协议分配委托时出现编译器错误
【发布时间】: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


    【解决方案1】:

    发行说明的已知问题部分说:

    您不能有条件地分配给可选对象的属性。 (16922562)

    例如,这是不支持的:

    let window: NSWindow? = NSApplication.sharedApplication.mainWindow
    window?.title = "Currently experiencing problems"
    

    所以你应该做类似if let realObject = object { ... }

    【讨论】:

      猜你喜欢
      • 2021-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多