我正在调用一个期望String...
可变参数的方法,但它允许从封闭函数接收的唯一内容是普通String
。
我的方法如下:
public func deleteKeys(keysReceived:String..., completionHandler:@escaping () -> Void)
{
RedisClient.getClient(withIdentifier: RedisClientIdentifier()) {
c in
do {
let client = try c()
client.delete(keys: keysReceived){}
completionHandler()
}
//...
}
}
编译错误是
Cannot convert value of type '[String]' to expected argument type 'String'
此方法(client.delete()
)来自Redis API for Perfect-Swift,因此我无法更改签名,但我可以更改封闭函数(deleteKeys)。我也无法直接调用函数,因为它在回调闭包中
关于如何将接收到的variadic参数传递给封闭的可变参数函数的任何建议?我可以将数组分解为单个字符串并单独删除,但这似乎不是很有效
答案 0 :(得分:2)
可变参数意味着它是一个后跟三个点的类型,例如String...
它们用于传递可变数量的相同类型的值。您不能将方法的可变参数传递给另一个方法。在方法内部,它变成了一个Array
,它不能作为一个变量传递而没有大量的技巧,你真的不想在这个例子中烦恼。
但是,我们可以从source看到:
public extension RedisClient {
/// Get the key value.
func delete(keys: String..., callback: @escaping redisResponseCallback) {
self.sendCommand(name: "DEL \(keys.joined(separator: " "))", callback: callback)
}
}
他们正在做的就是以空格作为分隔符加入Array
。因此,您可以将其添加到顶级的自己的代码中:
public extension RedisClient {
/// Get the key value.
func delete(keys: [String], callback: @escaping redisResponseCallback) {
self.delete(keys: keys.joined(separator: " "), callback: callback)
}
}
然后你可以用:
来调用它client.delete(keys: keysReceived){}
请注意,这仅适用于此特定情况,因为在内部,原始方法会转换字符串:
delete(keys: "one", "two", "three"){}
为:
["one", "two", "three"]
然后到:
"one two three"
我手动执行此操作并将最后一个字符串传递给:
delete(keys: "one two three"){}
变为:
["one two three"]
然后是joined
:
"one two three"
因此,当调用self.sendCommand
时,最终结果是相同的。
这很可能不适用于其他可变方法,因为它依赖于内部使用joined
方法的方法。
答案 1 :(得分:1)
我认为你必须使用一些替代方案,因为根据文件
传递给可变参数的值在其中可用 函数的主体作为适当类型的数组
所以要么你可以在getClient的回调中进行工作,要么将字符串逗号分开,或者正如你所说的那样
我可以将数组分解为单个字符串并单独删除
或者您可以这样做:
func deleteKeyForAPI(_ receivedKeys: String...) {
//here reveivedKeys is an array...
print(receivedKeys) //here you can separate keys
}
func yourDeleteKeyFunction(_ receivedKeys: String){
deleteKeyForAPI(receivedKeys)
}
let myKeys = "s1, s2, s3"
yourDeleteKeyFunction(myKeys)