键入“Any”没有下标成员(firebase) [英] Type 'Any' has no subscript members (firebase)

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

问题描述

我收到此错误:尝试运行此代码块时,键入任何没有下标成员:

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!.dynamicType NSDictionary ,请使用可选的cast 作为? 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天全站免登陆