Result of call is unused

别等时光非礼了梦想. 提交于 2019-12-04 04:11:44

问题


Right below the second comment, I receive an error of "Result of call to 'taskForDeleteMethod' is unused. Why is this when I use the results and error in the closure following the call?

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

回答1:


You are confusing the results variable, which is, indeed, used inside the closure, and the result of the taskForDELETEMethod call itself, which is NSURLSessionDataTask object.

From the examples of using taskForDELETEMethod that I was able to find online it looks like it is perfectly OK to ignore the return value, so you can avoid this warning by assigning the result to _ variable, i.e.

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



回答2:


In earlier swift versions, you need not bother about the return value of a method. You may store it in any variable snd use it later or you may ignore it completely. Neither it gave any error nor a warning.

But in swift 3.0 you need to specify whether you want to ignore the returned value or use it.

1. If you want to use the returned value, you can create a variable/constant and store the value in it, i.e

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

2. If you want to ignore the returned value, you can use _ ,i.e

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


来源:https://stackoverflow.com/questions/39692602/result-of-call-is-unused

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!