Swift - 无法将“__NSCFString”类型的值转换为“NSDictionary”

Posted

技术标签:

【中文标题】Swift - 无法将“__NSCFString”类型的值转换为“NSDictionary”【英文标题】:Swift - Could not cast value of type '__NSCFString' to 'NSDictionary' 【发布时间】:2016-08-08 14:17:48 【问题描述】:

我收到此错误,但我正在尝试从 Dictionary 获取 String。这是我的代码:

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
            

        )

在我的 Firebase 数据库中,"name""login" 都是字符串。我不明白这是什么问题。

任何帮助将不胜感激!

【问题讨论】:

问题将快照转换为 NSDictionary。调试时检查 snaphsot 内容 snapshotvalue 是字符串,您正在尝试将该值转换为字典。 @lubilis,我需要使用 if let 构造。非常感谢你!你救了我! 欢迎朋友:)快乐编码:) 【参考方案1】:

关于快照转换到 NSDictionary 的问题。由于快照值是一个字符串。 试试这个:

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
            
        
    )

【讨论】:

以上是关于Swift - 无法将“__NSCFString”类型的值转换为“NSDictionary”的主要内容,如果未能解决你的问题,请参考以下文章