Compiler error when assigning the Delegate for a P

2019-03-05 08:34发布

问题:

I have a problem assigning the delegate for an object that is an instance of a class that defines a protocol in Swift as follows:

I simplified the code to the bare bones to exemplify the issue: This is the class with the protocol

protocol TheProtocol {
    func notifyDelegate()
}
class ClassWithProtocol: NSObject {   
    var delegate: TheProtocol?
    fire() {
        delegate?.notifyDelegate()
    }
}

This is the class the conforms to the Protocol

    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()
        }
    }

I have tried all sort of alternatives to assign the delegate without success. Any idea what I am missing?

回答1:

The Known Issues section of the Release Notes says:

You cannot conditionally assign to a property of an optional object. (16922562)

For example, this is not supported:

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

So you should do something like if let realObject = object { ... }