Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift 3 issue with CVarArg being passed multiple times

Tags:

swift

I have below code in swift 3:

 class StringUtility {

  static func Localizer(tableName: String?) -> (_ key: String, _ params: CVarArg...) -> String {
    return { (key: String, params: CVarArg...) in

      let content = NSLocalizedString(key, tableName: tableName, comment: "")

      if params.isEmpty {
        return content
      }

      print(params) ->>>>>> this prints [[[Wells Fargo]]]
      return NSString.init((format: content, arguments: getVaList(params))) as String
    }
  }
}

func localizationHelper(tableName: String, key: String, params: CVarArg...) -> String {
  let t = StringResourceUtility.Localizer(tableName: tableName)
  print(params) - >>>>>>>>>> this prints [[Wells Fargo]]
  return t(key, params)
}

If you see the print statements in above two functions, [] are appended every time CVarArg is passed inside functions resulting in wrong localization string outputted.

1) CVarArg cannot be passed multiple times like in above code ? 2) how to fix this ?

like image 647
user1452936 Avatar asked Dec 03 '22 13:12

user1452936


1 Answers

You cannot pass a variable argument list to another function, you have to pass a CVaListPointer instead. Also withVaList should be used instead of getVaList:

class StringResourceUtility {

    static func Localizer(tableName: String?) -> (_ key: String, _ params: CVaListPointer) -> String {
        return { (key: String, params: CVaListPointer) in
            let content = NSLocalizedString(key, tableName: tableName, comment: "")
            return NSString(format: content, arguments: params) as String
        }
    }
}

func localizationHelper(tableName: String, key: String, params: CVarArg...) -> String {
    let t = StringResourceUtility.Localizer(tableName: tableName)
    return withVaList(params) { t(key, $0) } 
}

Example:

let s = localizationHelper(tableName: "table", key: "%@ %@", params: "Wells", "Fargo")
print(s) // Wells Fargo
like image 137
Martin R Avatar answered Mar 08 '23 04:03

Martin R