Why doesn't swift allow me to create a protocol type field?

52 Views Asked by At

As I know, structure is a value type and it stores all it's fields nearby in a continuous memory segment, the size of which should be known at the time of compilation. So, as I think, because of the constant size of the reference to some object, there shouldn't be a problem to compile this code:

struct Some {
    weak var delegate: SomeDelegate?
}

protocol SomeDelegate {
    ...some functions...
}

So struct 'Some' will have only one field with 32 or 64 bit size(how I think it should be). But swift compiler issues an error to this lines and says:

"'weak' must not be applied to non-class-bound 'any SomeDelegate'; consider adding a protocol conformance that has a class bound" Of course I can do this task with generics or associated types, but why "'weak' must not be applied to non-class-bound 'any SomeDelegate'"?

1

There are 1 best solutions below

0
On

You can use weak with protocols if you make your protocol conform to AnyObject

struct Some {
    weak var delegate: (any SomeDelegate)?
}

protocol SomeDelegate: AnyObject {
    ...
}

Weak (reference) can only be used with reference types. Structs and enums are value types, classes are reference types.

This is why the protocol must be a class-only (AnyObject) protocol