Weak property in a Swift protocol may only be a class or class-bound protocol type

前提是你 提交于 2019-12-09 00:38:14

问题


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' 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 }

}

回答1:


Protocols can't currently require properties to be implemented as weak stored properties.

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

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.

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 saying
associatedtype ViperViewClass : AnyObject).



来源:https://stackoverflow.com/questions/47699813/weak-property-in-a-swift-protocol-may-only-be-a-class-or-class-bound-protocol-ty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!