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?
weak
is a qualifier for reference types (as opposed to value types, such as struct
s and built-in value types).
Reference types let you have multiple references to the same object. The object gets deallocated when the last strong reference stops referencing it (weak references do not count).
Value types, on the other hand, are assigned by copy. Reference counting does not apply, so weak
modifier does not make sense with them.