【问题标题】:Function gives Unexpected non-void return value in void function [duplicate]函数在void函数中给出了意外的非void返回值[重复]
【发布时间】:2016-09-04 00:08:34
【问题描述】:

我有一个应该获取 json 数据并返回它的函数。这是下面的函数:

func httpjson(){
    let requestURL: NSURL = NSURL(string: "http://www.learnswiftonline.com/Samples/subway.json")!
    let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithRequest(urlRequest) { (data, response, error) -> Void in
        let httpResponse = response as! NSHTTPURLResponse
        let statusCode = httpResponse.statusCode
        if (statusCode == 200) {
            print("All OK!")
            do{
                let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
                return json
            }catch {
                print("Error with Json: \(error)")
            }
        }
    }
    task.resume()
}

代码返回错误Unexpected non-void return value in void function

在阅读了有关此问题的一些信息后,我了解到可以通过将 func httpjson(){ 更改为 func httpjson()-> String{ 来解决此问题,但它仍然返回相同的错误。

【问题讨论】:

  • 非常类似于this

标签: swift


【解决方案1】:

问题似乎在于定义为(data, response, error) -> Void 的闭包,而不是httpjson 方法。

由于您的数据任务是异步的,所以在 JSON 解析完成时,httpjson 已经返回。它不需要被定义为返回任何东西,因为还没有任何to返回。

您需要对json 执行一些操作(通知、回调、完成块等),以便让应用程序的其余部分知道何时可以使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-15
    • 2023-03-09
    • 2018-01-24
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多