Credit for extending Selector goes entirely to Andyy Hope (@AndyyHope) who posted this article on Medium:
He looks at the problem of Swift selector syntax being somewhat unwieldy, and turns it into
[code language=”plain”]fileprivate extension Selector {
static let buttonTapped =
#selector(ViewController.buttonTapped(_:))
}[/code]
Thanks to fileprivate, you don’t get namespacing conflicts.
Awesome. So I head over to an application where I’m using selectors, add my file extension and update my addObserver implementation to …
NotificationCenter.default.addObserver(self, selector: .saveContent, name: NSNotification.Name("SaveNeeded"), object: nil)
That’s much better, but name: NSNotification.Name(“SaveNeeded”) is still pretty damn unwieldy.
And thus, I have now added
[code language=”plain”]struct NotificationString {
static let saveNeeded = NSNotification.Name(“SaveNeeded”)
}[/code]
to my project as well, which leaves me with
NotificationCenter.default.addObserver(self, selector: .saveContent, name: NotificationString.saveNeeded, object: nil)
which is much more readable, and easier to type. It also means that I keep track of all notification names in one place where I can annotate them without cluttering up my core classes.
Jan 8 2017
Awesome Extensions: Selector
Credit for extending Selector goes entirely to Andyy Hope (@AndyyHope) who posted this article on Medium:
He looks at the problem of Swift selector syntax being somewhat unwieldy, and turns it into
[code language=”plain”]fileprivate extension Selector {static let buttonTapped =
#selector(ViewController.buttonTapped(_:))
}[/code]
Thanks to fileprivate, you don’t get namespacing conflicts.
Awesome. So I head over to an application where I’m using selectors, add my file extension and update my addObserver implementation to …
NotificationCenter.default.addObserver(self, selector: .saveContent, name: NSNotification.Name("SaveNeeded"), object: nil)
That’s much better, but name: NSNotification.Name(“SaveNeeded”) is still pretty damn unwieldy.
And thus, I have now added
[code language=”plain”]struct NotificationString {static let saveNeeded = NSNotification.Name(“SaveNeeded”)
}[/code]
to my project as well, which leaves me with
NotificationCenter.default.addObserver(self, selector: .saveContent, name: NotificationString.saveNeeded, object: nil)
which is much more readable, and easier to type. It also means that I keep track of all notification names in one place where I can annotate them without cluttering up my core classes.
By Extelligent Cocoa • Extensions, Wiki • • Tags: NotificationCentre, NSNotification.Name, Selector