与雨燕ARGS ...功能通过与ARGS另一个函数 [英] Swift function with args... pass to another function with args
问题描述
我有一个简单的问题。我试着搜索在许多博客关于这个问题,但所有的网站迅速返回工作怎么样的功能,但我需要这种情况。
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
(的va_list
的斯威夫特相当于C),并调用一个函数,
需要 CVaListPointer
参数。
Similar as in (Objective-)C, you cannot pass a variable argument list
directly to another function. You have to create a CVaListPointer
(the Swift equivalent of va_list
in C) and call a function which
takes 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 list
and calls the closure with this pointer as argument.
示例(从的NSString
文档):
let msg = "%@: %f\n".getLocalizeWithParams("Cost", 1234.56)
print(msg)
有关美国地区输出:
Cost: 1,234.560000
有关德语区域输出:
Cost: 1.234,560000
这篇关于与雨燕ARGS ...功能通过与ARGS另一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!