Tony Stark Tony Stark - 3 months ago 20
Swift Question

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


I was just wondering why keyword
weak
can only applied to class and class-bound protocol types? What is the reason behind it? Thanks in advance for any help!

Answer

weak is a qualifier for reference types (as opposed to value types, such as structs 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.