title: Hooking up UIButton to closure? (Swift, target-action)
body: <p>I want to hook up a UIButton to a piece of code – from what I have found, the preferred method to do this in Swift is still to use the <code>addTarget(target: AnyObject?, action: Selector, forControlEvents: UIControlEvents)</code> function. This uses the <code>Selector</code> construct presumably for backwards compatibility with Obj-C libraries. I think I understand the reason for <code>@selector</code> in Obj-C – being able to refer to a method since in Obj-C methods are not first-class values.</p>
  
  <p>In Swift though, functions are first-class values. Is there a way to connect a UIButton to a closure, something similar to this:</p>
  
  <pre><code>// -- Some code here that sets up an object X
  
  let buttonForObjectX = UIButton() 
  
  // -- configure properties here of the button in regards to object
  // -- for example title
  
  buttonForObjectX.addAction(action: {() in 
  
    // this button is bound to object X, so do stuff relevant to X
  
  }, forControlEvents: UIControlEvents.TouchUpOutside)
  </code></pre>
  
  <p>To my knowledge, the above is currently not possible. Considering that Swift looks like it's aiming to be a quite functional, why is this? The two options could clearly co-exist for backwards compatibility. Why doesn't this work more like onClick() in JS? It seems that the <em>only</em> way to hook up a UIButton to a target-action pair is to use something that exists solely for backwards compatibility reasons (<code>Selector</code>).</p>
  
  <p>My use case is to create UIButtons in a loop for different objects, and then hook each up to a closure. (Setting a tag / looking up in a dictionary / subclassing UIButton are dirty semi-solutions, but I'm interested in how to do this functionally, ie this closure approach)</p>