When I'm declaring variables as weak
in Swift, I sometimes get the error message from Xcode:
'weak' may only be applied to class and class-bound protocol types
or
'weak' must not be applied to non-class-bound 'SomeProtocol'; consider adding a protocol conformance that has a class bound
I'm wondering why the keyword weak
can only applied to class and class-bound protocol types? What is the reason behind this requirement?
One common reason for this error is that you have declared you own protocol, but forgot to inherit from AnyObject
:
protocol PenguinDelegate: AnyObject { func userDidTapThePenguin() } class MyViewController: UIViewController { weak var delegate: PenguinDelegate? }
The code above will give you the error if you forget to inherit from AnyObject
. The reason being that weak
only makes sense for reference types (classes). So you make the compiler less nervous by clearly stating that the PenguinDelegate is intended for classes, and not value types.
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