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

喜欢而已 提交于 2019-12-24 05:47:17

问题


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

回答1:


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




回答2:


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@mail.com") { (success) in
    if success
    {
        // Email found
    }
    else{

    }
}

This link could be helpful



来源:https://stackoverflow.com/questions/39599142/can-someone-tell-me-why-i-keep-getting-error-unexpected-non-void-return-value-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!