问题
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