Swift 协议中的弱属性可能只是一个类或类绑定的协议类型
我想定义一个在 Viper 架构中使用的协议,以使用具有弱属性的协议在 Viper 组件之间建立连接,但我收到以下错误消息:
I would like to define a protocol which is used in a Viper architecture to establish a connection between a Viper components using a protocol with a weak property but I get the following error message:
'weak' 只能应用于类和类绑定的协议类型,不是'Self.ViperViewClass'
'weak' may only be applied to class and class-bound protocol types, not 'Self.ViperViewClass'
protocol ViperPresenter: class {
associatedtype ViperViewClass
weak var view: ViperViewClass! { get set }
}
协议目前不能要求将属性实现为 weak
存储属性.
Protocols can't currently require properties to be implemented as weak
stored properties.
虽然 weak
和 unowned
关键字目前在属性要求中是允许的,但它们没有任何作用.以下是完全合法的:
Although the weak
and unowned
keywords are currently allowed on property requirements, they have no effect. The following is perfectly legal:
class C {}
protocol P {
weak var c: C? { get set }
}
struct S : P {
var c: C? // strong reference to a C instance, not weak.
}
这是作为错误提交,并且SE-0186 将使用weak
和 unowned
在协议中的属性要求 Swift 4.1 中的警告(在 Swift 3 和 4 模式下),以及 Swift 5 中的错误.
This was filed as a bug, and SE-0186 will make the use of weak
and unowned
on property requirements in a protocol a warning in Swift 4.1 (in both Swift 3 and 4 modes), and an error in Swift 5.
但即使协议可以要求将属性实现为weak
或unowned
存储属性,编译器也需要知道ViperViewClass
是一个类类型(也就是说, associatedtype ViperViewClass : AnyObject
).
But even if protocols could require properties to be implemented as weak
or unowned
stored properties, the compiler would need to know that ViperViewClass
is a class type (i.e by sayingassociatedtype ViperViewClass : AnyObject
).