Gimme some sugar. Series 3 — #selector

Aron Balog
1 min readMar 27, 2018

#selector — not an insta/twitter tagging concept, this is regular Swift syntax which is a bit different from other stuff in this beautiful language.

It is that one thing that is just weird. It has changed over the time and is still weird, probably because it’s still “in love” with Objective-C. We are here to break them apart as much as we can.

Probably the most common (old) approach:

...let button = UIButton()// self is `ViewController`
button.addTarget(self, action: #selector(close(_:)), for: .touchUpInside)

Gimme some sugar and make it sweeter.

fileprivate extension Selector {
static let close = #selector(ViewController.close(_:))
}

And now syntax is sweet, isn’t it?

button.addTarget(self, action: .close, for: .touchUpInside)

Notice that extension is fileprivate. This Selector extension should be visible just in this particular file, e.g. file where your target class resides.

--

--

Aron Balog

Unstoppable coder, passionate about software architecture, primarily focused on iOS development. https://github.com/aronbalog | https://twitter.com/Aron_Balog