【问题标题】:localizeWithFormat and variadic arguments in SwiftSwift 中的 localizeWithFormat 和可变参数
【发布时间】:2015-01-13 02:28:21
【问题描述】:

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

"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

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

【问题讨论】:

    标签: swift localization


    【解决方案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"
    

    init(format:locale:arguments:)

    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)
    

    【讨论】:

    • 抱歉,问题可能不清楚,但我的目标是创建通用的东西,使用可变参数
    • Thks Leonardo,这个编译但它不会让我翻译带有参数的本地化字符串,因为你没有使用 String.localizedStringWithFormat
    【解决方案2】:

    这允许带有可变参数的本地化字符串:

    extension String {
          func localizedStringWithVariables(vars: CVarArgType...) -> String {
            return String(format: NSLocalizedString(self, tableName: nil, bundle: NSBundle.mainBundle(), value: "", comment: ""), arguments: vars)
          }
    }
    

    调用方式:

    "Hello, %@. Your surname is: %@.".localizedStringWithVariables("Neil", "Peart")
    

    【讨论】:

      【解决方案3】:

      在 Swift 3 中

      func localize(key: String, arguments: CVarArg...) -> String {
        return String(format: NSLocalizedString(key, comment: ""), arguments)
      }
      

      【讨论】:

        猜你喜欢
        • 2016-08-11
        • 1970-01-01
        • 2014-07-27
        • 1970-01-01
        • 2010-12-12
        • 2020-02-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多