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
I was just wondering why keyword weak
can only applied to class and class-bound protocol types? What is the reason behind it?
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.