I'm trying to return a value for a function from inside of a nested function. I understand why it doesn't work, but I just need to know a workaround for my type of problem.
In my code, I'm checking whether or not a person has already been created inside of my Firebase Database. So inside of the usersRef function, you'll see that if the value return from firebase is "nil" then the user hasn't been created and vice versa.
When I say : return userBool it's giving me this error:
Unexpected non-void return value in void function
Been looking for a clean workaround, but the only thing I can think of is having to create this function over and over again for each of the various times I want to check it. Obviously, I'd rather not do that, haha, so if you could help me out by giving some suggestions on how to fix this and have a clean solution, let me know! :)
func checkIfUserExists(userID : String) -> Bool {
var userBool = Bool()
var usersRef = FIRDatabase.database().reference()
usersRef.child("users").child(userID).observeSingleEvent(of: .value, with: {
snapshot in
if snapshot.value != nil {
userBool = true
return userBool
}
else {
userBool = false
return userBool
}
})
}
UPDATE :
Thanks to your suggestions, I added a completion, and it worked perfectly. :)
func checkIfUserExists(userID : String, completion: @escaping (_ success: Bool) -> ()){
var userBool = Bool()
var usersRef = FIRDatabase.database().reference()
usersRef.child("users").child(userID).observeSingleEvent(of: .value, with:{
snapshot in
if snapshot.value != nil {
print("userBool!", userBool)
userBool = true
}
else {
print("userBool2!", userBool)
userBool = false
}
completion(userBool)
})
}