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

Jorge Bernal me at koke.me
Sat Dec 5 10:21:18 CST 2015


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/20151205/5312b46d/attachment.html>


More information about the swift-evolution mailing list