Nathan Levitt Nathan Levitt - 3 months ago 108
iOS Question

Type 'Any' has no subscript members (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 = ""
}
}


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

Answer

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 ?? ""