How to properly use VarArgs for localizing strings?

后端 未结 1 420
猫巷女王i
猫巷女王i 2020-12-19 07:44

I have a String extension that helps me internationalise.

public extension String {
    var localized: String {
        return NSLocalizedString(self, table         


        
相关标签:
1条回答
  • 2020-12-19 08:14

    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
            }
        }
    }
    

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

    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)
        }
    

    Now

    "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";
    
    0 讨论(0)
提交回复
热议问题