What is the difference between a var
and a weak var
in Swift?
This has to do with how ARC manages memory of your objects.
Using var
defines a strong reference to the object, while using weak var
defines a weak reference to the object.
Objects are kept in memory for as long as there remains one or more strong references to that object. Using a weak reference allows you to hold a reference to an object without increasing what is known as its "retain count".
If nothing else holds a reference to your weak var
, the object will be deallocated, and your weak var
will decay to nil
.1 This won't happen when you just use var
, as this defines a strong reference to the object, which should prevent it from deallocating.
This is identical to how "strong" vs "weak" works in Objective-C, and I recommend you read this answer, as it applies exactly to Swift.
1As a Swift specific note, this is the reason why anything declared as a weak var
must be an optional type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With