title: How to write a generic apply() function in Swift?
body: <p>Is there any way to get the following working in Swift 3?</p>
  
  <pre><code> let button = UIButton().apply {
          $0.setImage(UIImage(named: "UserLocation"), for: .normal)
          $0.addTarget(self, action: #selector(focusUserLocation), 
                       for: .touchUpInside)
          $0.translatesAutoresizingMaskIntoConstraints = false
          $0.backgroundColor = UIColor.black.withAlphaComponent(0.5)
          $0.layer.cornerRadius = 5
       }
  </code></pre>
  
  <p>The <code>apply&lt;T&gt;</code> function should take a closure of type <code>(T)-&gt;Void</code>, run it passing <code>self</code> into it, and then simply return <code>self</code>. </p>
  
  <p>Another option would be to use an operator for this like "<code>=&gt;</code>"
  (borrowed the idea from <a href="https://stackoverflow.com/tags/kotlin/info">Kotlin</a> and <a href="https://stackoverflow.com/tags/xtend/info">Xtend</a> languages).</p>
  
  <p>Tried to do extension of <code>NSObject</code> like this:</p>
  
  <pre><code>extension NSObject {   
      func apply&lt;T&gt;(_ block: (T)-&gt;Void) -&gt; T
      {
          block(self as! T)
          return self as! T
      }
  }
  </code></pre>
  
  <p>But it requires explicit declaration of the parameter type in closure:</p>
  
  <pre><code>let button = UIButton().apply { (it: UIButton) in
          it.setImage(UIImage(named: "UserLocation"), for: .normal)
          it.addTarget(self, action: #selector(focusUserLocation), 
                       for: .touchUpInside)
          ...
  </code></pre>
  
  <p>This is not convenient and makes the whole idea not worth the effort. The type is already specified at object creation and it should be possible not to repeat it explicitly.</p>
  
  <p>Thanks!</p>