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 }
}
Protocols can be used for both reference types (classes) and value types (structs, enums). So in the likely case that you need to make a delegate weak, you have to make it an object-only protocol. The way to do that is to add AnyObject to the protocol's inheritance list.
A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements.
A protocol can have properties as well as methods that a class, enum or struct conforming to this protocol can implement. A protocol declaration only specifies the required property name and type.
Protocols allow you to group similar methods, functions, and properties. Swift lets you specify these interface guarantees on class , struct , and enum types. Only class types can use base classes and inheritance from a protocol.
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 sayingassociatedtype ViperViewClass : AnyObject
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With