为什么void函数中出现意外的非void返回值?

Wei*_*Xia 2 ios swift alamofire

我创建了一个从API获取URL的函数,并返回URL字符串作为结果.但是,Xcode给了我这个错误信息:

void函数中出现意外的非void返回值

有谁知道为什么会这样?

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
            }
        }
}
Run Code Online (Sandbox Code Playgroud)

Vas*_*vev 7

使用闭包而不是返回值:

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
}
Run Code Online (Sandbox Code Playgroud)