【问题标题】:Type 'Any' has no subscript members (firebase)类型“任何”没有下标成员(firebase)
【发布时间】:2017-01-01 08:09:00
【问题描述】:

在尝试运行此代码块时,我收到此错误:“类型 'Any' 没有下标成员”:

init(snapshot: FIRDataSnapshot) {
    key = snapshot.key
    itemRef = snapshot.ref

    if let postContent = snapshot.value!["content"] as? String {   // error
        content = postContent
    } else {
        content = ""
    }
}

我一直在寻找答案,但找不到使用 FireBase 解决此问题的答案。我该如何解决这个错误?

【问题讨论】:

  • 看起来你的快照有一个原始值,这意味着snapshot.value 不返回字典。检查 key 是什么(如果是 content,我不会感到惊讶)以及您正在观察的位置的 JSON 是什么。
  • print(snapshot.value!.dynamicType) 打印什么?
  • @vacawama 它显示它是一个 NSDictionary

标签: ios swift dictionary firebase firebase-realtime-database


【解决方案1】:

我还有一个代码片段,可让您访问子节点的值。希望对您有所帮助:

if let snapDict = snapShot.value as? [String:AnyObject] {

            for child in snapDict{

                let shotKey = snapShot.children.nextObject() as! FIRDataSnapshot

                if let name = child.value as? [String:AnyObject]{

                    var _name = name["locationName"]
                    print(_name)
                }

            }

        }

最好的问候, 纳扎尔·梅德罗斯

【讨论】:

    【解决方案2】:

    snapshot.value 的类型为Any?,因此您需要先将其转换为基础类型,然后才能对其下标。由于snapshot.value!.dynamicTypeNSDictionary,所以使用可选转换as? NSDictionary 来建立类型,然后您可以访问字典中的值:

    if let dict = snapshot.value as? NSDictionary, postContent = dict["content"] as? String {
        content = postContent
    } else {
        content = ""
    }
    

    或者,您可以将其作为单线:

    content = (snapshot.value as? NSDictionary)?["content"] as? String ?? ""
    

    【讨论】:

    • 如何获取子节点的值?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-05
    相关资源
    最近更新 更多