类型“Any"没有下标成员(firebase) [英] Type 'Any' has no subscript members (firebase)

查看:22
本文介绍了类型“Any"没有下标成员(firebase)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试运行此代码块时收到此错误:Type 'Any' has no subscript members":

I am getting this error: "Type 'Any' has no subscript members" when trying to run this block of code:

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

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

我一直在寻找答案,但找不到可以通过 FireBase 解决此问题的答案.我该如何解决这个错误?

I have been searching for an answer and couldn't find one that solved this problem with FireBase. How would I solve this error?

推荐答案

snapshot.value 的类型为 Any?,所以需要将其强制转换为底层类型在你可以下标之前.由于 snapshot.value!.dynamicTypeNSDictionary,使用可选的演员 as?NSDictionary 建立类型,然后就可以访问字典中的值了:

snapshot.value has the type Any?, so you need to cast it to the underlying type before you can subscript it. Since snapshot.value!.dynamicType is NSDictionary, use an optional cast as? NSDictionary to establish the type, and then you can access the value in the dictionary:

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

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

Or, you can do it as a one-liner:

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

这篇关于类型“Any"没有下标成员(firebase)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆