title: Weak reference to closure in Swift
body: <p>I have the following code to create an observable property for data binding.  It's in the works so I'm not sure what the final implementation is going to be and I'm still pretty new to Swift.</p>
  
  <pre><code>class Observable&lt;T&gt; {
      typealias Observer = T -&gt; Void
  
      var value: T {
          didSet {
              for observer in self.observers {
                  observer?(self.value)
              }
          }
      }
  
      var observers: [Observer?] = []
  
      init(_ val: T) {
          self.value = val
      }
  }
  </code></pre>
  
  <p>I would like to keep weak references to the Observer closures.  I don't want to rely on the client to ensure that the closure is weak/unowned before passing it in, via the capture list.  Especially because there can be many observable properties on a given class.  </p>
  
  <p>Is it possible to make the closure references weak in my Observable class?</p>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>I found a couple of resources that I think will help me accomplish what I want:</p>
  
  <p><a href="https://stackoverflow.com/questions/25613783/make-self-weak-in-methods-in-swift">Make self weak in methods in Swift</a></p>
  
  <p>specifically,</p>
  
  <pre><code>func methodPointer&lt;T: AnyObject&gt;(obj: T, method: (T) -&gt; () -&gt; Void) -&gt; (() -&gt; Void) {
    return { [unowned obj] in method(obj)() }
  }
  </code></pre>
  
  <p>The following link refers to the above stackoverflow answer and goes into some more detail:</p>
  
  <p><a href="http://blog.xebia.com/2014/10/09/function-references-in-swift-and-retain-cycles/" rel="noreferrer">http://blog.xebia.com/2014/10/09/function-references-in-swift-and-retain-cycles/</a></p>
  
  <p>and this is a two-way binding example:</p>
  
  <p><a href="http://five.agency/solving-the-binding-problem-with-swift/" rel="noreferrer">http://five.agency/solving-the-binding-problem-with-swift/</a></p>
  
  <p>specifically,</p>
  
  <pre><code>class BondBox&lt;T&gt; {
    weak var bond: Bond&lt;T&gt;?
    init(_ b: Bond&lt;T&gt;) { bond = b }
  }
  </code></pre>
  
  <p>where the listener is wrapped in a class called Bond, which is weakly referenced in the BondBox. </p>