Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 }

}
like image 320
Blazej SLEBODA Avatar asked Dec 07 '17 16:12

Blazej SLEBODA


People also ask

How do you make a protocol weak in Swift?

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.

What is class protocol in Swift?

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.

CAN protocols have properties in Swift?

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.

Can a protocol inherit from a class Swift?

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.


Video Answer


1 Answers

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

like image 173
Hamish Avatar answered Oct 23 '22 04:10

Hamish