Enzo
Enzo

Reputation: 73

Swift 2.2 - value is not persisted after function execution

I created the function above to check if a user exists on Firebase database:

func userExists(userUid: String) -> Bool {
    var userExists: Bool = false
    DBRef.child("users").child(userUid).observeSingleEventOfType(.Value, withBlock: { (snapshot: FIRDataSnapshot) in
        if snapshot.exists(){
            userExists = true
        }else{
            userExists = false
        }
    })
    return userExists
}

The problem is that the userExists function always returns "false", even if the userExists variable is setted as true inside the withBlock. Any help, please? Thanks!

Upvotes: 0

Views: 49

Answers (1)

aramusss
aramusss

Reputation: 2401

You should not use return and closure blocks in the same function, because the function will return the value before the block is executed. You can use something like this:

func userExists(userUid: String, completion: (exists: Bool) -> Void) {
    var userExists: Bool = false
    DBRef.child("users").child(userUid).observeSingleEventOfType(.Value, withBlock: { (snapshot: FIRDataSnapshot) in
        if snapshot.exists(){
            completion(true)
        }else{
            completion(false)
        }
    })
}

Then, you just call:

if userExists(userId, completion: {
    // Code here
})

Upvotes: 1

Related Questions