在过去,使用objective-c,我的本地化类使用宏来从变量名生成密钥 . 目的是允许 auto-completionremove the need to add a comment ,提供一种在代码中添加 base language 的简单方法,并保留键值对 in one place . 它类似于以下内容:

Localize(_theKey, "The default string")

其中 Localize 是预处理器宏:

#define GenerateKey(key) [NSString stringWithFormat:@"%@.%@", CapitalizedClassName, [(@"" #key) substringFromIndex:1]]

#define Localize(key, defaultValue) key = NSLocalizedStringWithDefaultValue(GenerateKey(key), DefaultTable, DefaultBundle, defaultValue, DefaultComment)

最终,这将生成一个初始化的属性,如下所示:

_theKey = NSLocalizedStringWithDefaultValue("Localization.Generic.theKey", DefaultTable, DefaultBundle, "The default string", "")

我可以在我的代码中访问本地化的字符串

[Localization Generic].theKey

我知道预处理器在Swift中不可用,但有没有办法实现同样的目的呢?

TL;DR; Is there any way I can use a macro1 to use a variable name to generate code in Swift?

我希望答案是“不” . 但如果我错了,我会感到惊喜!

1.由于缺乏更好的术语,任何解决方案都是好的!