[英]Swift. unowned may only be applied to class and class-bound protocol types. weak works fine
Please read the question to the end as it seems to be the duplicate of many similar others but it is not. 请将问题读到最后,因为它似乎是许多类似其他人的副本,但事实并非如此。 Most of the other questions use closures with
let
keyword to capture weak or unowned self before object init. 大多数其他问题使用带有
let
关键字的闭包来捕获对象init之前的弱或无主自我。 I do not. 我不。
My code: 我的代码:
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)
}
When I try to compile I get an error highlighted on unowned var responder : ObserverProtocol!
当我尝试编译时,我在
unowned var responder : ObserverProtocol!
上突出显示错误unowned var responder : ObserverProtocol!
'unowned' may only be applied to class and class-bound protocol types, not 'ObserverProtocol!'
'unowned'可能只适用于类和类绑定协议类型,而不是'ObserverProtocol!'
If I change unowned
to weak
I can compile. 如果我将
unowned
变为weak
我可以编译。
There is clearly some concept about unowned
that I don't understand, so I would appreciate if someone could explain it to me. 显然有一些我不理解的关于
unowned
概念,所以如果有人能向我解释,我将不胜感激。
PS I am aware of multiple questions similar to this: PS我知道类似这样的多个问题:
UIView, CMDeviceMotionHandler : unowned may only be applied to class and class-bound protocol types UIView,CMDeviceMotionHandler:unowned只能应用于类和类绑定协议类型
But I suppose this is not my case. 但我想这不是我的情况。
As you already know, unowned
cannot be optional but weak
may be nil
at some point. 如你所知,
unowned
是不可选的,但weak
在某些时候可能是nil
。
From what I understand, unowned
variable is different from implicitly unwrapping optionals. 据我所知,
unowned
变量与隐式展开选项不同。 Implicit unwrapping is for variables, which may be nil
, but we already know this variable is not nil
at the exact point of access. 隐式展开是针对变量的,可能是
nil
,但我们已经知道这个变量在准确的访问点并不是 nil
。 However, unowned
variable can never be nil
at any point. 但是,
unowned
变量在任何时候都不能nil
。
Thus, you can't use unowned
constant of type ObserverProtocol!
因此,您不能使用
ObserverProtocol!
类型的unowned
常量ObserverProtocol!
. 。 You need to get rid of
!
你需要摆脱
!
. 。
But if you do get rid of !
但如果你真的摆脱了
!
, Observer
needs an initializer that initializes responder
. ,
Observer
需要初始化器来初始化responder
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.