Swift 调用的结果未使用
在第二条注释的正下方,我收到一个错误“调用'taskForDeleteMethod'的结果未使用。为什么在调用后的闭包中使用结果和错误时会出现这种情况Swift 调用的结果未使用,swift,function,closures,Swift,Function,Closures,在第二条注释的正下方,我收到一个错误“调用'taskForDeleteMethod'的结果未使用。为什么在调用后的闭包中使用结果和错误时会出现这种情况 func deleteSession(_ completionHandlerForDeleteSession: @escaping (_ success: Bool, _ error: NSError?) -> Void) { /* 1. Specify parameters, method (if has {key}), and
func deleteSession(_ completionHandlerForDeleteSession: @escaping (_ success: Bool, _ error: NSError?) -> Void) {
/* 1. Specify parameters, method (if has {key}), and HTTP body (if POST) */
// There are none...
/* 2. Make the request */
taskForDELETEMethod { (results, error) in
/* 3. Send the desired value(s) to completion handler */
if let error = error {
print("Post error: \(error)")
completionHandlerForDeleteSession(false, error)
} else {
guard let session = results![JSONKeys.session] as? [String: AnyObject] else {
print("No key '\(JSONKeys.session)' in \(results)")
return
}
if let id = session[JSONKeys.id] as? String {
print("logout id: \(id)")
completionHandlerForDeleteSession(true, nil)
}
}
}
}
您混淆了
results
变量(实际上,它在闭包中使用)和taskForDELETEMethod
调用本身的结果(即NSURLSessionDataTask
对象)
从我在网上找到的使用taskForDELETEMethod
的例子来看,忽略返回值似乎是完全可以的,因此您可以通过将结果分配给
变量来避免此警告,即
let _ = taskForDELETEMethod {
... // The rest of your code goes here
}
在早期的swift版本中,您无需担心方法的返回值。您可以将其存储在任何变量中,稍后再使用,也可以完全忽略它。它既不会给出任何错误,也不会给出警告 但是在swift 3.0中,您需要指定是要忽略返回值还是使用返回值 1。如果要使用返回值,可以创建一个变量/常量并将值存储在其中,即
let value = taskForDELETEMethod {
// Your code goes here
}
2。如果要忽略返回的值,可以使用\u,即
let _ = taskForDELETEMethod {
// Your code goes here
}
更好的是,您可以只执行“=method()”。当您不需要返回值时,您不必指定let。