Swift - unexpected non-void return value in void function
You are missing return type in your method header.
func calculateDistance(location: CLLocation) -> CLLocationDistance {
Seemingly my answer looks as an inferior duplicate, so some addition.
Functions (including methods, in this case) declared without return types are called as void function, because:
func f() {
//...
}
is equivalent to:
func f() -> Void {
//...
}
Usually, you cannot return any value from such void functions.
But, in Swift, you can return only one value (I'm not sure it can be called as "value"), "void value" represented by ()
.
func f() {
//...
return () //<- No error here.
}
Now, you can understand the meaning of the error message:
unexpected non-void return value in void function
You need to change the return value or else change the return type Void
to some other type.
Unexpected non-void return value in void function Swift3
The problem is that you are trying to return a non-void value from inside a closure, which only returns from the closure, but since that closure expects a void return value, you receive the error.
You cannot return from an asynchronous function using the standard return ...
syntax, you have to declare your function to accept a completion handler and return the value from the async network call inside the completion handler.
func findChat(string: String, completion: @escaping (Chat?)->()) {
var returnValue: (Chat?)
let url = getChatsURL
let Parameters = [ "title" : string ]
Alamofire.request("\(url)", method: .post, parameters: Parameters).validate().responseString { response in
if let anyResponse = response.result.value {
self.responseFromServer = anyResponse
}
if self.responseFromServer == "" {
completion(nil)
} else {
let ref = DatabaseReference.chats.reference()
let query = ref.queryOrdered(byChild: "uid").queryEqual(toValue: (self.responseFromServer))
query.observe(.childAdded, with: { snapshot in
completion(Chat(dictionary: snapshot.value as! [String : Any]))
})
}
}
}
Then you can call this function and use the return value like this:
findChat(string: "inputString", completion: { chat in
if let chat = chat {
//use the return value
} else {
//handle nil response
}
})
Unexpected non-void return value in void function (Swift 3)
If you are calling an async method like Alamofire.request
, then you need notify when this async method is over with closures
Try with this
func postUser(username: String, pass: String, finishedClosured:@escaping ((Bool)->Void)) {
Alamofire.request("https://someAPI.com/auth/login", method: .post, parameters: ["email": contact, "password": pass], encoding: URLEncoding.default, headers: ["Accept":"application/json"]).responseJSON { (response) in
switch(response.result) {
case .success(let value):
let json = JSON(value)
print("JSON: \(json)")
print(json["data"]["result"])
finishedClosured(true)
case .failure(let error):
print(error)
finishedClosured(false)
}
}
}
Use it
self.postUser(username: "your UserName", pass: "Your Pass") { (result) in
if(result){
debugPrint("All is fine")
}else{
debugPrint("All is wrong")
}
}
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 - Swift 4 (Firebase, Firestore)
Since the firebase operation gives you a callback closure, and the calls made asynchronously, I believe it wont be possible for you to directly return from closures. However, you can return an escaping closure indicating true or false as follows...
func checkUserWith(email: String, completion: @escaping (Bool) -> Void)
{
let usersDB = database.collection("users")
usersDB.whereField("email", isEqualTo: email).getDocuments { (snapshot, error) in
if error != nil
{
print("Error: \(error?.localizedDescription ?? "")")
completion(false)
}
for document in (snapshot?.documents)! {
if document.data()["email"]! as! String == email {
completion(true)
return
}
}
completion(false)
}
}
Then when you call this method:
checkUserWith(email: emailHere) { (isSucceeded) in
if isSucceeded {
//it exists, do something
} else {
//user does not exist, do something else
}
}
Unexpected non-void return value in void function when returns an array
You can´t just return words
in your closure
. First of all it´s an async method second you need to return a value outside of the closure which will be called before the closure. You need to have a completionHandler
instead of returning Array<Any>
. In that case you can pass the value if and when it succeeds. Something like this:
func getWords(onCompletion: @escaping (Array<Any>) -> Void) {
ref = Database.database().reference()
ref.child("addedWords").observe(.value, with: { (DataSnapshot) in
var tempWords = DataSnapshot.value as! [String:AnyObject]
var words = Array(tempWords.keys)
print(words)
onCompletion(words)
})
}
To call it:
getWords(onCompletion: { (words) in
print(words)
})
Related Topics
Swift: How to Open a New App When Uibutton Is Tapped
Can Not Save File Inside Tmp Directory
Save and Load from Keychain | Swift
Possible to Handle Your Own Http Url Schemes in iOS
How to Get Uiscrollview Vertical Direction in Swift
How to Compare Two Nsdate Objects in Objective C
Detecting If iPhone Is in a Dark Room
Error: Ld: Library Not Found for -Lpods with Cocoapods
Why Is Uitextfield.Text an Optional
In Swift, How to Let Other Apps Continue to Play Audio When My App Is Open
How to Debug an iOS Extension (.Appex)
Nsxmlparser: Unexpected Result with Non-Ascii Characters
Uibezierpath Triangle with Rounded Edges
Creating a Navigationcontroller Programmatically (Swift)
Find the Tangent of a Point on a Cubic Bezier Curve