Why does Unexpected non-void return value in void function happen?
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
}
Why i am getting Unexpected non-void return value in void function error while returning value in swift?
I think AuthManager.shared.saveAddressAsWorkHome(params) { (response) in
this is asynchronous
closure and you are try to return a value in it so you getting this error.
You can not return from asynchronous function directly. You have to add a completion handler on your method and return the value from async in completion handler
So you have to change your function
func getLatDestination(completion : @escaping (Double) -> ()){
var params = [String: Any]()
params[ParametersKeys.access_token] = KeyChain.getAccessToken()!
params[ParametersKeys.address] = googlePlaceObject?.results.first?.formattedAddress
params[ParametersKeys.latitude] = googlePlaceObject?.results.first?.geometry.location.lat
params[ParametersKeys.longitude] = googlePlaceObject?.results.first?.geometry.location.lng
params[ParametersKeys.googlePlaceId] = googlePlaceObject?.results.last?.placeId
params[ParametersKeys.login_type] = 1
AuthManager.shared.saveAddressAsWorkHome(params) { (response) in
if response.flag == RESPONSE_FLAGS.flag_143 {
if let addressData = response.response["addresses"] as? [[String: Any]] {
completion(addressData[0]["lat"])
}
}
}
And when you call your function
getLatDestination(completion: {ret in
print(ret)
})
Unexpected non-void return value in void function for return true
The method signature should have -> Bool
at the end. This tells the compiler that the method will return a boolean value. Check this.
Unexpected non-void return value in void function, return multiple values
First mistake here is that Alamofire.request...
is asynchronous. So you can't return a value fetched using that in your function.
The reason you are getting an error is because you are no longer in your function when you are trying to return. You are in the function that is the completion handler of the Alamofire request.
In order to get something out of this you will have to pass it into a completion handler of your own. Like this...
func calculateDistance(_ firstLat: Double, _ firstLong: Double, _ secondLat: Double, _ secondLong: Double, completionHandler: @escaping (Double, Double, String) -> ()) {
let URL = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=\(firstLat),\(firstLong)&destinations=\(secondLat),\(secondLong)&key=KEYID"
Alamofire.request(URL).responseJSON { response in
if let value = response.result.value {
let json = JSON(value)
let distance = json["rows"][0]["elements"][0]["distance"]["value"].double! / 1000 // Double
let price = distance * 1.0 // Double
let duration = json["rows"][0]["elements"][0]["duration"]["text"] // String
completionHandler(distance, price, duration) // Keep getting this error on this line
}
}
}
}
The signature (Double, Double, String) -> ()
is a function that takes in two Doubles
and a String
. When you get the data back from the network you are then calling this function.
Then you would call it like...
calculateDistance(1, 2, 3) { (distance, price, duration) in
// do something with the distance price and duration
}
Just another note here... It is really bad practice to squash the parameter names in your function by using _
. Do it (maybe) for the first parameter if it is obvious from the function name what it is but don't do it for the following parameters.
Unexpected Non-Void Return Value In Void Function (Swift 2.0)
You have a problem because your line:
return minions
does not return from your function. Instead, it returns from the completion handler in dataTaskWithRequest
. And it shouldn't be doing so because that closure is a void function.
The problem which you have results from the fact that dataTaskWithRequest
is an asynchronous operation. Which means that it can return later after executing your function.
So, you need to change your design pattern.
One way of doing that would be the following:
static var minions:[Minion] = [] {
didSet {
NSNotificationCenter.defaultCenter().postNotificationName("minionsFetched", object: nil)
}
}
class func fetchMinionData() {
var myURL = "http://myurl/test.json"
let dataURL = NSURL(string: myURL)
let request = NSURLRequest(URL: dataURL!, cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 5.0)
let session = NSURLSession.sharedSession()
session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
let minionJSON = JSON(data!)
var minions = [Minion]()
for (_, minionDictionary) in minionJSON {
minions.append(Minion(minionDetails: minionDictionary))
}
self.minions = minions
//THIS IS WHERE THE ERROR OCCURS
}).resume()
}
Then before calling your function you should register to listen for NSNotification
with name "minionsFetched". And only after you get that notification you should process the minions as if they were fetched.
Unexpected non-void return value in void function swift 4 using json serialisation
You can't return data directly from an asynchronous task. Use a closure
Create a Function using a closure like.
func jsonSerialisation(jsonUrl: String, completion block: @escaping ((NSArray) -> ())){
let url = URL(string: JsonUrl)
let task = URLSession.shared.dataTask(with: url!) { (data, responce, error) in
if let e = error{
print(e.localizedDescription)
}
else{
if let content = data{
do {
if let Json = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSArray{
block(Json)
}
}
catch let error{
print(error.localizedDescription)
}
}
}
}
task.resume()
}
And Call :
jsonSerialisation(jsonUrl: "Your Url") { (json) in
print(json)
}
This is helpful
dispatch_async and unexpected non-void return value in void function in Swift
The problem is
dispatch_async(dispatch_get_global_queue(priority, 0)) {
and
dispatch_async(dispatch_get_main_queue()) {
are actually creating closures/functions, so any code within them will relate to that function, not
func handleLocation() -> CLLocation {
If you're doing an asynchronous operation within a function, you can't really have a return statement after the asynchronous operation is completed. Instead, you should use a completion handler in your function. e.g.:
func aSyncFunction(completionHandler: (AnyObject) -> ()) {
//do async opporation
completionHandler("finished") // call the completion block when finished
}
Here's how I would implement it for your use case:
func handleLocation(completionBlock: (CLLocation?) -> ()) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
guard let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate else {
dispatch_async(dispatch_get_main_queue()) {
completionBlock(nil)
}
return
}
appDelegate.startGPS()
while (!appDelegate.isLocationFixed()) {
sleep(1)
}
dispatch_async(dispatch_get_main_queue()) {
completionBlock(appDelegate.getLocation())
}
}
}
example usage:
handleLocation { (location: CLLocation?) in
if let location = location {
//use valid location
}
}
Getting non--void error on function return
Look carefully where your return statement belongs. It's not returning from ParseInt
, it's actually returning from the completion closure passed to URLSession.shared.dataTask
. The return type of that completion handler is void
.
func dataTask(with request: URLRequest, completionHandler: @escaping
(Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask
Why: Non-void function should return a value
Change return to return(tempNews)
Because you are returning null where a type of [News] expected
Proper statement
else { return tempNews}
Related Topics
Load a .Tmx (Tiled Map) in Sprite Kit
How to Draw on an Image in Swift
Alert When New Version of iOS App Is Available
Static VS Class as Class Variable/Method (Swift)
The 'Pods' Target Has Transitive Dependencies That Include Static Binaries' When Installing Gcm
Objective-C Rabbitmq Client Not Publishing Messages to Queue
Uitableviewcell Textlabel Color Not Changing
Protocol Extension, Mutating Function
Swrevealviewcontroller - Rightviewcontroller
How to Find the Kind of Errors a Method May Throw and Catch Them in Swift
Check If My iOS Application Is Updated
JSON Parsing Using Nsjsonserialization in iOS
Dyld: Library Not Loaded for a Framework Within a Framework
How Get the List of Paired Bluetooth Devices in Swift
Pdfkitten Is Highlighting on Wrong Position
Can the -Objc Flag Be Applied Selectively to Static Libraries