Swift 中的 localizeWithFormat 和可变参数 [英] localizeWithFormat and variadic arguments in Swift

查看:36
本文介绍了Swift 中的 localizeWithFormat 和可变参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to create a String extension to do something like that

"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

Type CVaListPointer does not conform to protocol CVargType

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

Anyone knows how to work aroundthis compilation error?

推荐答案

这应该很简单,只需将参数更改如下:

This should be pretty simple just change your parameters as follow:

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)

这篇关于Swift 中的 localizeWithFormat 和可变参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆