Tarvo Mäesepp Tarvo Mäesepp - 1 year ago 66
Swift Question

Converting Firebase value(Int) to String leads to error

I am trying to get some values from my JSON tree which is in Firebase however I am getting error:

Could not cast value of type '__NSCFNumber' (0x1a7c497f0) to
'NSString' (0x1a7c55398).

The way I set the value is this:

let values = ["username": username, "email": email, "reputation": reputation] as [String : Any]

I get value like this:

self.databaseRef.child("users").child(self.loggedInUser!.uid).observeSingleEvent(of: .value) { (snapshot:FIRDataSnapshot) in

//store the logged in users details into the variable

let snapshot = snapshot.value as! [String: AnyObject]
self.usernameLabel.text = snapshot["username"] as! String
self.reputationLabel.text = snapshot["reputation"] as! String//This is giving me error

What I am doing wrong? What is causing this? In Swift 2 it worked but not in Swift 3.

Answer Source

The data you're retrieving from firebase is probably of type double. try using this :

self.reputationLabel.text = "\(snapshot["reputation"])"


if this is giving you nil, try to use a conditional unwrap :

if let reputation = snapshot["reputation"] {
    self.reputationLabel.text = "\(reputation)"
} else {
    print("reputation is nil")

if your data is nil then check your data name in firebase, and your objects in the db