Search code examples
swifttypesprotocolsweak-references

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


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 }

}

Solution

  • 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).