Moonwalker4z Moonwalker4z - 2 months ago 46
Swift Question

Can someone tell me why I keep getting error "unexpected non-void return value in void function"

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)
}

Answer

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