Reputation: 85
I get an error when trying to return a true or false Bool value... Can someone help ? I was trying to check if user exists in Firebase database.
func checkIfUserExists(email: String) -> Bool{
FIRDatabase.database().reference().child("users").observe(.childAdded, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject]{
switch email {
case dictionary["email"] as! String!:
return true
break
default:
return false
break
}
}
}, withCancel: nil)
}
Upvotes: 1
Views: 308
Reputation: 721
change it this way
func checkIfUserExists(email: String, results:(exists:Bool)->Void){
FIRDatabase.database().reference().child("users").observe(.childAdded, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject]{
switch email {
case dictionary["email"] as! String!:
results(true)
break
default:
results(false)
break
}
}
}, withCancel: nil)
}
The function can be called like this
checkIfUserExists(email: "some email", results:{ exists
if exists {
//do something
}
else{
// user do not exist... do something
}
})
@ohr answer should be the acepted one, this is only a clarification
Upvotes: 0
Reputation: 1727
Your return is inside a closure, not your function. What comes to mind is you could return a closure in your function like this
func checkIfUserExists(email: String, completion:(success:Bool) -> ())
And then once your FIRDatabase closure ends instead of return true or false you
completion(success:true) // or false
And use it like this.
checkIfUserExists("[email protected]") { (success) in
if success
{
// Email found
}
else{
}
}
This link could be helpful
Upvotes: 2