0

When declaring notification names, is there any way to avoid mistakes like this?

extension Notification.Name {
    static let userHasLoggedIn = Notification.Name("userHasLoggedIn")
    //oops! developer forgot to change the literal...
    static let userHasLoggedOut = Notification.Name("userHasLoggedIn")
}

I am hoping for some kind of way to use the variable name as the notification name without having to re-type it. Something like this:

extension Notification.Name {
    //wishful thinking??
    static let userHasLoggedIn = Notification.Name(#fieldname)
    static let userHasLoggedOut = Notification.Name(#fieldname)
}
Mike Taverne
  • 9,156
  • 2
  • 42
  • 58

2 Answers2

0

You could use Sourcery.

I haven't used it but it's a code generator that uses templates to generate boilerplate code.

You could create a template or rule (sorry, don't know the actual terms) that converts userHasLoggedIn into static let userHasLoggedIn = Notification.Name("userHasLoggedIn").

EmilioPelaez
  • 18,758
  • 6
  • 46
  • 50
-2

You can use enumerators with a String like so:

enum Names: String {
    case logIn = "userHasLoggedIn"
    case logOut = "userHasLoggedOut"
}

Then in your code, you can say:

static let userHasLoggedIn = Notification.Name(Names.logIn.rawValue)
static let userHasLoggedOut = Notification.Name(Names.logOut.rawValue)
akmin04
  • 677
  • 6
  • 14
  • 1
    The question is asking how to avoid copy and paste errors in the string literal value. This does not address that question. – rmaddy Nov 30 '18 at 23:35