Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between a var and a weak var in Swift [duplicate]

What is the difference between a var and a weak var in Swift?

like image 925
nonamexd Avatar asked Apr 05 '15 20:04

nonamexd


1 Answers

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.

like image 95
nhgrif Avatar answered Oct 11 '22 22:10

nhgrif