微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

swar 3问题与CVarArg被多次传递

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

如果在上面两个函数中看到print语句,每次在函数内部传递CVararg时都会附加[],导致输出错误的本地化字符串.

1)CVararg不能像上面的代码一样多次传递?
2)如何解决这个问题?

解决方法

你不能将变量参数列表传递给另一个函数
必须传递一个CVaListPointer.还有withVaList应该
用来代替getVaList:

class StringResourceUtility {

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

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

例:

let s = localizationHelper(tableName: "table",key: "%@ %@",params: "Wells","Fargo")
print(s) // Wells Fargo

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐