ios – 类型’Any’没有下标成员(firebase)

我收到此错误:“尝试运行此代码块时,键入’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的类型为Any?,因此您需要先将其强制转换为基础类型,然后才能下标.由于snapshot.value!.dynamicType是NSDictionary,使用可选的强制转换为? 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 ?? ""

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...