2

I have a Strings.h file with many entries like:

#define HIDE_WORD NSLocalizedString(@"Hide", @"the word on a button to Hide a screen that is showing")

How can I make those macros available to Swift, or what's an alternate if I can't make the macros available? Is the best approach to wrap the macros I want available in Swift in class methods?

This answer doesn't work in my case because NSLocalizedString(@"Foo", @"Bar") isn't constant.

Andrew Johnson
  • 13,108
  • 13
  • 75
  • 116
  • Your link just points to the question. Wouldn't https://stackoverflow.com/a/26709119/278842 work for you? – Christopher Oezbek Aug 21 '17 at 18:04
  • 1
    Using macros just to shorten your code is bad code style. If localizations are done correctly, a string is never used twice (definitely not with the same comment), therefore I see no point to even have a global Strings file in the first place. The correct solution is to manually write `NSLocalizedString` everywhere. – Sulthan Aug 21 '17 at 18:10
  • @ChristopherOezbek That's what I'm doing (that non-accepted answer), I was wondering if there was something better. – Andrew Johnson Aug 21 '17 at 19:26
  • @Sulthan Interesting. What happens if I use the word "Hide" for a UIBarButtonItem title, in multiple places in the code? It seems like then the comment would be the same? In that case, do you mean I should make the entire UIBarButtonItem instantiation inside maybe a MyStyles class and call that rather than having the macro for the title? What if I use the word Hide in both a UIBarButtonItem and a UIButton for some reason? – Andrew Johnson Aug 21 '17 at 19:30
  • 1
    @AndrewJohnson If the button does always the same thing, there is no reason why you should repeat the creating pattern in different places. If the button does something slightly different somewhere, then it should have a separate comment. The problem with maintaining a separate strings file is that it is almost never updated when functionality changes, therefore you get unused strings, outdated comments etc. – Sulthan Aug 21 '17 at 19:33
  • Thanks for your comments @Sulthan – Andrew Johnson Aug 21 '17 at 19:45

1 Answers1

0

As there is no automated way to get these strings into Swift without editing the code, you might as well put all of the data directly into Swift.

How about a regular expression approach for this?

Search

\#define (\w*) NSLocalizedString\(@"([^"]*)", *@"([^"]*)"\)

replace

let $1 = NSLocalizedString\("$2", comment: "$3"\)
Christopher Oezbek
  • 23,994
  • 6
  • 61
  • 85