小编典典

Swift中的localizeWithFormat和可变参数

swift

我正在尝试创建一个字符串扩展来做类似的事情

"My name is %@. I am %d years old".localizeWithFormat("John", 30)

看起来像这样

extension String {
  func localizeWithFormat(arguments: CVarArgType...) -> String {
    return String.localizedStringWithFormat(
      NSLocalizedString(self,
        comment: ""), getVaList(arguments))
  }
}

它给我以下编译错误

类型CVaListPointer不符合协议CVargType

有人知道如何解决此编译错误吗?


阅读 319

收藏
2020-07-07

共1个答案

小编典典

这应该非常简单,只需更改您的参数,如下所示:

extension String {
    func localizeWithFormat(name:String,age:Int, comment:String = "") -> String {
        return String.localizedStringWithFormat( NSLocalizedString(self, comment: comment), name, age)
    }
}

"My name is %@. I am %d years old".localizeWithFormat("John", age: 30)  // "My name is John. I am 30 years old"

初始化(格式:语言环境:参数:)

extension String {
    func localizeWithFormat(args: CVarArgType...) -> String {
        return String(format: self, locale: nil, arguments: args)
    }
    func localizeWithFormat(local:NSLocale?, args: CVarArgType...) -> String {
        return String(format: self, locale: local, arguments: args)
    }
}
let myTest1 = "My name is %@. I am %d years old".localizeWithFormat(NSLocale.currentLocale(), args: "John",30)
let myTest2 = "My name is %@. I am %d years old".localizeWithFormat("John",30)
2020-07-07