【问题标题】:Result of call is unused调用结果未使用
【发布时间】:2016-09-25 22:57:49
【问题描述】:

在第二条评论的正下方,我收到一条错误消息:“未使用 'taskForDeleteMethod' 的调用结果。为什么当我在调用后的闭包中使用结果和错误时会出现这种情况?

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)
            }
        }
    }
}

【问题讨论】:

    标签: swift function closures


    【解决方案1】:

    早期的 swift 版本中,您不必担心方法的返回值。您可以将它存储在任何变量中并稍后使用它,或者您可以完全忽略它。它既没有给出任何错误,也没有给出警告。

    但是在 swift 3.0 中你需要指定是忽略返回值还是使用它。

    1。如果要使用返回值,可以创建一个变量/常量并将值存储在其中,即

    let value = taskForDELETEMethod {
        // Your code goes here
    }
    

    2。如果要忽略返回值,可以使用 _ ,即

    let _ = taskForDELETEMethod {
        // Your code goes here
    }
    

    【讨论】:

    • 更好的是,你可以只做'_ = method()'。当您不需要返回值时,您不必指定 let。
    【解决方案2】:

    您混淆了results 变量(实际上是在闭包内部使用)和taskForDELETEMethod 调用本身的结果,即NSURLSessionDataTask 对象。

    从我在网上找到的使用taskForDELETEMethod 的示例看来,忽略返回值是完全可以的,因此您可以通过将结果分配给_ 变量来避免此警告,即

    let _ = taskForDELETEMethod {
        ... // The rest of your code goes here
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-06
      • 1970-01-01
      • 2018-02-10
      • 1970-01-01
      相关资源
      最近更新 更多