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

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

问题描述

我有一个字符串扩展可以帮助我国际化.

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 访问权限"

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

Actual result: "Please grant ( MyApp ) GPS access"

我在这里遗漏了什么?

推荐答案

你不能将变量参数列表传递给另一个函数,你必须传递一个 CVaListPointer 代替(Swift 等价物va_list in C):

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天全站免登陆