Type 'Any' has no subscript members (firebase)

前端 未结 2 1584
走了就别回头了
走了就别回头了 2020-11-29 08:54

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

init(snapshot: FIRDataSnapshot) {
    key = snapsh         


        
相关标签:
2条回答
  • 2020-11-29 09:20

    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 ?? ""
    
    0 讨论(0)
  • 2020-11-29 09:33

    I have also a codepiece which allows you to access to the values of the child nodes. I hope this helps you:

    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)
                    }
    
                }
    
            }
    

    Best regards, Nazar Medeiros

    0 讨论(0)
提交回复
热议问题