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

前端之家收集整理的这篇文章主要介绍了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解决这个问题的答案.我该如何解决这个错误

@H_502_6@

解决方法

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 ?? ""
@H_502_6@ @H_502_6@ 原文链接:https://www.f2er.com/iOS/332513.html

猜你在找的iOS相关文章