Why does Unexpected non-void return value in void function happen? [duplicate]

落爺英雄遲暮 提交于 2019-11-30 07:48:01

问题


I created a function to get URL from API, and return URL string as the result. However, Xcode gives me this error message:

Unexpected non-void return value in void function

Does anyone know why this happens?

func getURL(name: String) -> String {

        let headers: HTTPHeaders = [
            "Cookie": cookie
            "Accept": "application/json"
        ]

        let url = "https://api.google.com/" + name

        Alamofire.request(url, headers: headers).responseJSON {response in
            if((response.result.value) != nil) {
                let swiftyJsonVar = JSON(response.result.value!)

                print(swiftyJsonVar)

                let videoUrl = swiftyJsonVar["videoUrl"].stringValue

                print("videoUrl is " + videoUrl)

                return (videoUrl)   // error happens here
            }
        }
}

回答1:


Use closure instead of returning value:

func getURL(name: String, completion: @escaping (String) -> Void) {
    let headers: HTTPHeaders = [
        "Cookie": cookie
        "Accept": "application/json"
    ]
    let url = "https://api.google.com/" + name
    Alamofire.request(url, headers: headers).responseJSON {response in
        if let value = response.result.value {
            let swiftyJsonVar = JSON(value)
            print(swiftyJsonVar)
            let videoUrl = swiftyJsonVar["videoUrl"].stringValue
            print("videoUrl is " + videoUrl)
            completion(videoUrl)
        }
    }
}

getURL(name: ".....") { (videoUrl) in
    // continue your logic
}



回答2:


You cant return value from inside closer so you need to add closure to your function

func getURL(name: String , completion: @escaping (_ youstring : String) -> (Void) ) -> Void {

            let headers: HTTPHeaders = [
                "Cookie": cookie
                "Accept": "application/json"
            ]

            let url = "https://api.google.com/" + name

            Alamofire.request(url, headers: headers).responseJSON {response in
                if((response.result.value) != nil) {
                    let swiftyJsonVar = JSON(response.result.value!)

                    print(swiftyJsonVar)

                    let videoUrl = swiftyJsonVar["videoUrl"].stringValue

                    print("videoUrl is " + videoUrl)
                     completion (youstring :  )
                      // error happens here
                }
            }
    }


来源:https://stackoverflow.com/questions/43923189/why-does-unexpected-non-void-return-value-in-void-function-happen

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