请将问题读到最后,因为它似乎是许多类似其他人的副本,但事实并非如此。大多数其他问题使用带有let
关键字的闭包来捕获对象init之前的弱或无主的自我。我没有。
我的代码:
class Singleton : ObserverProtocol {
static let shared = Singleton()
private let obs : Observer = Observer.init()
private init() { self.obs.responder = self }
func observe(_ object : Any) {}
fileprivate class Observer : NSObject {
unowned var responder : ObserverProtocol!
func observe(_ obj : Any) {
self.responder.observe(obj)
}
}
}
fileprivate protocol ObserverProtocol : class {
func observe(_ object : Any)
}
当我尝试编译时,我在unowned var responder : ObserverProtocol!
'unowned'可能只适用于类和类绑定协议类型,而不是'ObserverProtocol!'
如果我将unowned
更改为weak
,我可以编译。
显然有一些关于unowned
的概念,我不明白,所以如果有人能向我解释,我会很感激。
P.S。我知道类似的多个问题:
UIView, CMDeviceMotionHandler : unowned may only be applied to class and class-bound protocol types
但我想这不是我的情况。
答案 0 :(得分:13)
As you already know, unowned
cannot be optional but weak
may be nil
at some point.
From what I understand, unowned
variable is different from implicitly unwrapping optionals. Implicit unwrapping is for variables, which may be nil
, but we already know this variable is not nil
at the exact point of access. However, unowned
variable can never be nil
at any point.
Thus, you can't use unowned
constant of type ObserverProtocol!
. You need to get rid of !
.
But if you do get rid of !
, Observer
needs an initializer that initializes responder
.