Tim Lupo Tim Lupo - 3 months ago 9
Swift Question

Nested Bool Always Returns Nil

I'm having a problem with this Swift function and although I'm sure the solution is fairly straightforward I cannot figure out what is wrong. Here is the code:

static func isArtist(user:FIRUser) -> Bool? {
var artist: Bool?
database.child("users").child(user.uid).observeSingleEventOfType(.Value, withBlock: { (snapshot) in
artist = true //retrieves bool, simplified for example
}) { (error) in
print("isArtist - data could not be retrieved - EXCEPTION: " + error.localizedDescription)
}
return artist
}


The function returns
nil
every time, when logically I would think it would return
true
. Is this a problem with nested functions? How can I return content in the nested function? The database is the implementation of the Swift Firebase SDK, and the function should only return nil if no such object can be retrieved (for this example, if
artist
is nil). Thanks.

Answer

Use completionBlock: to handle your situation , The reason why this is going to return you a nil is because you have declared your artist variable as optional , and it takes some time to retrieve data from any backend(asynchronous calls) thus executing return artist even before you could retrieve some value from database:-

Use :-

static func isArtist(user:FIRUser, completionBlock : ((isArtistBool : Bool)-> Void)) {
    database.child("users").child(user.uid).observeSingleEventOfType(.Value, withBlock: { (snapshot) in
             completionBlock(isArtistBool : true) //returns Bool in completionHnadler

        }) { (error) in

           print("isArtist - data could not be retrieved - EXCEPTION: " + error.localizedDescription)
          }

}

When you would call your function isArtist :-

isArtist(FIRAuth.auth()!.currentUser, completionBlock : {(isArtistBool) in 
 //Will return `isArtistBool` in completionHandler
 ..//rest of the code
})