如何正确使用VarArgs本地化字符串? [英] How to properly use VarArgs for localizing strings?

查看:108
本文介绍了如何正确使用VarArgs本地化字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个String扩展名,可以帮助我进行国际化.

I have a String extension that helps me internationalise.

public extension String {
    var localized: String {
        return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: "")
    }

    func localized(args:CVarArg...) -> String{
        return NSString.localizedStringWithFormat(self.localized as NSString, args) as String
    }
}

这样,我可以轻松地在应用程序中的任何位置使用"hello_world" .localized,并且效果很好.

This way I can easily use "hello_world".localized anywhere in the app and it works nicely.

现在,我希望具有相同的功能,但也希望能够传递参数.但是,传递"CVarArg ..."似乎不起作用,正如我期望的那样.

Now I want to have the same functionality, but also want to be able to pass arguments. However passing the 'CVarArg...' doesn't seem to work as I'd expect it to.

"grant_gps_access".localized("MyApp")

预期结果:请授予MyApp GPS访问权限"

实际结果:请授予(\ n MyApp \ n)GPS访问权限"

我在这里想念什么?

推荐答案

您不能将变量参数列表传递给另一个函数,您 必须通过CVaListPointer代替(Swift等效项 在C中的va_list中):

You cannot pass a variable argument list to another function, you have to pass a CVaListPointer instead (the Swift equivalent of va_list in C):

public extension String {
    var localized: String {
        return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: "")
    }

    func localized(args: CVarArg...) -> String {
        return withVaList(args) {
            NSString(format: self.localized, locale: Locale.current, arguments: $0) as String
        }
    }
}

由于NSString.localizedStringWithFormat没有变体,因此 VAListPointer,等效于NSString(format:, locale:, arguments:) 使用当前语言环境.

Since NSString.localizedStringWithFormat has no variant taking a VAListPointer, the equivalent NSString(format:, locale:, arguments:) with the current locale is used.

更简单(归因于@OOPer):使用 String.init(format:locale:arguments:)需要一个 [CVarArg]参数:

Even simpler (attribution goes to @OOPer): Use String.init(format:locale:arguments:) which takes a [CVarArg] argument:

    func localized(args: CVarArg...) -> String {
        return String(format: self.localized, locale: Locale.current, arguments: args)
    }

现在

"grant_gps_access".localized(args: "MyApp")

应按预期工作,假设字符串文件包含 条目

should work as expected, assuming that the strings file contains the entry

"grant_gps_access" =  "Please grant %@ GPS access";

这篇关于如何正确使用VarArgs本地化字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆