8

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 = ""
    }
}

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

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Nathan
  • 949
  • 8
  • 19
  • 2
    It looks like your snapshot has a primitive value, which means `snapshot.value` does not return a dictionary. Check what `key` is (I wouldn't be surprised if that is `content`) and what the JSON is at the location you are observing. – Frank van Puffelen Aug 25 '16 at 03:08
  • what does `print(snapshot.value!.dynamicType)` print? – vacawama Aug 25 '16 at 03:16
  • @vacawama it prints that it is a NSDictionary – Nathan Aug 25 '16 at 03:44

2 Answers2

18

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 ?? ""
vacawama
  • 150,663
  • 30
  • 266
  • 294
2

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

Nazar Medeiros
  • 437
  • 4
  • 10