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
}
}
}
Return from void functions in C++ The void functions are called void because they do not return anything. “A void function cannot return anything” this statement is not always true. From a void function, we cannot return any values, but we can return something other than values.
In lieu of a data type, void functions use the keyword "void." A void function performs a task, and then control returns back to the caller--but, it does not return a value. You may or may not use the return statement, as there is no return value.
In functions that have non-void return types (dont worry, we'll cover "void" later), a value is returned by the function when we call it. We know a function has a non-void return type by looking for a return type in the first line of the function definition or a return statement in the body of the function.
Any method declared void doesn't return a value. It does not need to contain a return statement, but it may do so.
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
}
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
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With