[swift-evolution] Allow Selectors to be used as Closures

Chris Byatt byatt.chris at gmail.com
Mon Dec 7 05:18:21 CST 2015


Jorge's second suggestion seems like a good one - it definitely makes more
sense to lay it out that way than the current usage of strings which makes
me cry a little bit..

It would be nice to eliminate the need for "myFunction"/"myFunction:".

Chris

On Sat, 5 Dec 2015 at 16:21 Jorge Bernal <me at koke.me> wrote:

> I think this has more to do with the UIKit API than the Swift language,
> but since we’re discussing it, here’s my 2¢
>
> On 04 Dec 2015, at 19:49, Chris Byatt <byatt.chris at gmail.com> wrote:
>
> We should be able to do:
>
> UIBarButtonItem(title: "Press", style: .Done, target: self, action: {
>     // Do Something})
>
> If action is just a closure, why is target needed? This example doesn’t
> match what was proposed in the subject “Selectors to be used as Closures”.
> I see a couple solutions to this:
>
> 1. Make it UIBarButtonIttem(title:style:action:), and pass any closure.
> That’s the most flexible, but as David mentioned it makes it too easy to
> create reference cycles.
> 2. Keep the target/action pattern, but make action’s type match the
> expected selector signature. To avoid cycles, the button item would keep a
> weak reference to self, and only call action if target != nil
>
> class MyController: UIViewController {
>     override func viewDidLoad() {
>         super.viewDidLoad()
>
>         self.navigationItem.rightBarButtonItem = UIBarButtonItem(title:
> "Press", style: .Done, target: self, action: MyController.functionToCall)
>     }
>
>     func functionToCall(button: UIBarButtonItem) {
>         // Do stuff
>     }
> }
>
>
> --
> Jorge Bernal | jbernal at gmail.com | jorge at automattic.com
> Mobile Engineer @ Automattic | http://automattic.com/
>
> http://koke.me/ | http://jorgebernal.es/ | http://twitter.com/koke
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151207/598e5e31/attachment.html>


More information about the swift-evolution mailing list