Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can the keyword "weak" only be applied to class and class-bound protocol types

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?

like image 527
Thor Avatar asked Aug 09 '16 02:08

Thor


1 Answers

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.

like image 66
Jak Avatar answered Sep 23 '22 17:09

Jak