5

Is it possible to override a global function in Swift?

Specifically, I want to override NSLocalizedString. This was easy in Objective-c (#undef / #define), but in Swift NSLocalizedString is defined as a global function, and I cannot find a way to override it.

I could make my own function MyLocalizedString, which called the original NSLocalizedString, but then I would lose the clever support that AppCode has for Localizable.strings files (autocompletion of localization-keys, IDE showing the localized text) and I would have to ensure that every use of NSLocalizedString in my code is replaced with MyLocalizedString.

Edit: What do I want to achieve? I want to be able to dynamically change the strings in the GUI. The easiest is to redefine NSLocalizedString and then look up the string in a table myself. If it is not there, I will use the original string from Localizable.strings.

JRV
  • 1,702
  • 1
  • 17
  • 27
  • BTW: This is also very attractive for unit testing – JRV Jan 15 '15 at 08:16
  • Did you tried just to put your own implementation outside of a class, withoud the override keyword? – Dániel Nagy Jan 15 '15 at 08:19
  • Autocompletion works for your own functions as well, and you *can* define your own NSLocalizedString. What exactly are you trying to achieve? – Martin R Jan 15 '15 at 08:31
  • Martin R: When I mentioned autocompletion, I was referring to AppCode's ability to investigate the Localizable.strings file. It will most likely not be able to do autocompletion for the localized keys if I make my own function. – JRV Jan 15 '15 at 08:37
  • Daniel Nagy: I am not sure, what you mean? Yes, I have tried making a NSLocalizedString function outside a class, but that causes the compiler to complain about ambiguous methods – JRV Jan 15 '15 at 08:38
  • Is the autocompletion of localization-keys a special feature of AppCode (I never noticed that in Xcode)? Perhaps you should add that information to the question. – And you are right about the "ambiguous use" error, that seems to be a problem if you define a function with the same signature. – Martin R Jan 15 '15 at 08:56
  • Yes, it is an AppCode feature (though it still only works for Objective-c, but I am sure it will soon be coming for Swift as well, and I wouldn't want to be without it when it comes). Changed the text to be more specific about the IDE support – JRV Jan 15 '15 at 09:19
  • 1
    (@JRV: If you want to reply to someone then you should prefix the user name with the at-sign, e.g. `@MartinR ... your comment ...`. This ensures that the user is notified about your reply. See http://stackoverflow.com/editing-help#comment-formatting for details.) – Martin R Jan 15 '15 at 09:37
  • See my answer here: http://stackoverflow.com/a/33697088/8047... I think it's the same question without all the unit-testing appcode baggage. – Dan Rosenstark Nov 13 '15 at 16:13

0 Answers0