Junior — Middle
Is it possible to declare a weak reference as a constant, and in what cases is this permissible?
sobes.tech AI
Answer from AI
In Swift, a weak reference (weak) must always be declared as a variable (var), not as a constant (let). This is because a weak reference automatically becomes nil when the object it refers to is deallocated from memory. If a weak reference were a constant, its value could not be changed to nil, which contradicts the logic of weak references.
Therefore, declaring a weak reference as a constant is impossible and meaningless. A correct example of declaration:
class MyClass {
weak var delegate: SomeDelegate?
}
If you need the reference to be a constant, you can use a strong reference (let), but then it will not be weak and could lead to retain cycles.