title: Know when a weak var becomes nil in Swift?
body: <p>Let's say I have a <code>weak var view: UIView?</code> in my <code>class Button {}</code>. Is there any way to know when <code>view</code> loses its reference and becomes <code>nil</code>?</p>
  
  <p>I tried using <code>weak var view: UIView? {}</code> (aka a computed property) in order to override <code>set {}</code>, but that didn't work because now it's a computed property and can't store a weak reference (how annoying!).</p>
  
  <p><strong>Edit:</strong></p>
  
  <p><strong>@fqdn</strong>'s answer didn't work with this code... Try it in an Xcode Playground</p>
  
  <pre><code>import UIKit
  
  class Test {
    weak var target: UIView? {
      willSet {
        if !newValue { println("target set to nil") }
        else { println("target set to view") }
      }
    }
  }
  
  class Button {
    var view: UIView? = UIView()
  }
  
  var t = Test()
  var b = Button()
  t.target = b.view
  b.view = nil // t.target's willSet should be fired here
  </code></pre>
  
  <p>Your output console should display:</p>
  
  <pre><code>target set to view
  target set to nil
  </code></pre>
  
  <p>My console displays</p>
  
  <pre><code>target set to view
  </code></pre>
  
  <p><code>b.view</code> is the strong reference for the UIView instance. <code>t.target</code> is the weak reference. Therefore, if <code>b.view</code> is set to <code>nil</code>, the UIView instance is deallocated and <code>t.target</code> will be equal to nil.</p>