Compiler error when assigning the Delegate for a P

2019-03-05 09:01发布

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条回答
唯我独甜
2楼-- · 2019-03-05 09:24

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 { ... }

查看更多
登录 后发表回答