Declaring constants without repetition

One of my main coding pet peeves is repetitiveness, so I'm trying to figure out how to simplify cases like this:

extension NSTouchBarItem.Identifier
  static let
      navigation = NSTouchBarItem.Identifier("myapp.nav"),
      staging = NSTouchBarItem.Identifier("myapp.staging"),
      stage = NSTouchBarItem.Identifier("myapp.stage"),
      revert = NSTouchBarItem.Identifier("myapp.revert"),
      unstage = NSTouchBarItem.Identifier("myapp.unstage"),
      unstageAll = NSTouchBarItem.Identifier("myapp.unstageall"),
      stageAll = NSTouchBarItem.Identifier("myapp.stageall")

Isn't there some way to clean up all those repeated references to NSTouchBarItem.Identifier? I thought I could at least reduce them all to just Identifier, but it turns out being inside the extension doesn't get you that.

The thing I'm itching to use is this:

prefix operator โ—Š // shift-opt-v
prefix func โ—Š<T>(string: StringLiteralType) -> T
  where T: RawRepresentable, T.RawValue == String
  return T(rawValue: string)!

...which lets me do fun stuff like โ—Š"myapp.nav" as long as the compiler can infer the type. It works well for function parameters, but for these static let things I don't know how to get there.

(The choice of โ—Š is kind of arbitrary. I just needed an unused legal Swift operator that's easy to type.)

1 Like

You can use โ€œSelfโ€ to shorten it a bit.


I swear I tried that and got an error... I tried again just now to make sure and it worked. :man_shrugging:

1 Like