Egor Kuznetsov
Egor Kuznetsov

Reputation: 95

Swift - Could not cast value of type '__NSCFString' to 'NSDictionary'

I got this error, but I'm trying to get a String from a Dictionary. This is my code:

FIRDatabase.database().reference().child("users").child(uid).observeEventType(.ChildAdded, withBlock: { (snapshot) in

            let dictionary = snapshot.value as! NSDictionary

            if let username = dictionary["name"] as? String {
                cell.name.text = username
            }

            if let userlogin = dictionary["login"] as? String {
                cell.login.text = userlogin
            }

        })

In my Firebase Database "name" and "login" are both Strings. I cannot understand what's the problem.

Any help would be greatly appreciated!

Upvotes: 7

Views: 10757

Answers (1)

lubilis
lubilis

Reputation: 4160

Issue regards snapshot cast to NSDictionary. Since snapshot value is a String. Try this:

FIRDatabase.database().reference().child("users").child(uid).observeEventType(.ChildAdded, withBlock: { (snapshot) in

        if let dictionary = snapshot.value as? NSDictionary {

            if let username = dictionary["name"] as? String {
                cell.name.text = username
            }

            if let userlogin = dictionary["login"] as? String {
                cell.login.text = userlogin
            }
        }
    })

Upvotes: 7

Related Questions