gpt4 book ai didi

swift 3 : Method expecting variadic String parameter can only receive single String argument

转载 作者:搜寻专家 更新时间:2023-11-01 06:15:32 25 4
gpt4 key购买 nike

我正在调用一个需要 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()) 来自 Perfect-Swift 的 Redis API,因此我无法更改签名,但我可以更改封闭函数 (deleteKeys)。我也不能直接调用该函数,因为它在回调闭包中

关于如何将接收到的可变参数传递给封闭的可变参数函数有什么建议吗?我可以将数组分解为单个字符串并单独删除,但这似乎效率不高

最佳答案

可变参数表示它是一个类型后跟三个点,例如 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"]

然后加入到:

"one two three"

所以调用self.sendCommand时最终结果是一样的。

这很可能不适用于其他可变参数方法,因为它依赖于在内部使用 joined 方法的方法。

关于 swift 3 : Method expecting variadic String parameter can only receive single String argument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45950971/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com