Junior — Middle
Kas võib nõrga viite deklareerida konstantina ja millal see on lubatud?
sobes.tech AI
Vastus AI-lt
In Swift, a weak reference (weak) must always be declared as a variable (var), not as a constant (let). This is because the weak reference automatically becomes nil when the object it refers to is deallocated from memory. If the 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:
class MyClass {
weak var delegate: SomeDelegate?
}
If you want the reference to be a constant, you can use a strong reference (let), but then it will not be weak and may lead to retain cycles.