问题描述
我有一个简单的问题.我尝试在许多博客中搜索有关此问题的内容,但所有站点都返回了 swift 工作中的功能,但我需要这个案例.
I have a simple problem. I tried search in many blogs about this question but all site return how function in swift work, but I need this case.
我的自定义函数是:
func getLocalizeWithParams(args:CVarArgType...)->String {
return NSString.localizedStringWithFormat(self, args); //error: Expected expression in list of expressions
}
如何使用 args 将我的 args 传递给其他系统函数?
How I do to pass my args to other system function with args?
提前致谢.
推荐答案
与 (Objective-)C 中类似,不能传递变量参数列表直接到另一个函数.你必须创建一个 CVaListPointer
(C 中 va_list
的 Swift 等价物)并调用一个函数接受一个 CVaListPointer
参数.
Similar as in (Objective-)C, you cannot pass a variable argument listdirectly to another function. You have to create a CVaListPointer
(the Swift equivalent of va_list
in C) and call a function whichtakes a CVaListPointer
parameter.
所以这可能就是您要找的:
So this could be what you are looking for:
extension String {
func getLocalizeWithParams(args : CVarArgType...) -> String {
return withVaList(args) {
NSString(format: self, locale: NSLocale.currentLocale(), arguments: $0)
} as String
}
}
withVaList()
从给定的参数列表创建一个 CVaListPointer
并使用此指针作为参数调用闭包.
withVaList()
creates a CVaListPointer
from the given argument listand calls the closure with this pointer as argument.
示例(来自 NSString
文档):
Example (from the NSString
documentation):
let msg = "%@: %f\n".getLocalizeWithParams("Cost", 1234.56)
print(msg)
美国语言环境的输出:
Cost: 1,234.560000
德语语言环境的输出:
Cost: 1.234,560000
更新:从 Swift 3/4/5 开始,可以将参数传递给
Update: As of Swift 3/4/5 one can pass the arguments to
String(format: String, locale: Locale?, arguments: [CVarArg])
直接:
extension String {
func getLocalizeWithParams(_ args : CVarArg...) -> String {
return String(format: self, locale: .current, arguments: args)
}
}
这篇关于带有 args 的 Swift 函数...使用 args 传递给另一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!