7

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

Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
nonamexd
  • 101
  • 1
  • 4
  • 5
    [How much research effort is expected of Stack Overflow users?](http://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) – Martin R Apr 05 '15 at 20:09

1 Answers1

17

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.

Community
  • 1
  • 1
nhgrif
  • 61,578
  • 25
  • 134
  • 173