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

我创build了一个从API获取URL的函数,并返回URLstring作为结果。 但是,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 } } } 

使用闭包而不是返回值:

 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 } 

你不能从内部返回值,所以你需要添加闭包到你的函数

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