Recibo este error: “Escriba ‘Cualquiera’ no tiene miembros de subíndice” al intentar ejecutar este bloque de código:
init(snapshot: FIRDataSnapshot) { key = snapshot.key itemRef = snapshot.ref if let postContent = snapshot.value!["content"] as? String { // error content = postContent } else { content = "" } }
He estado buscando una respuesta y no pude encontrar una que resolviera este problema con FireBase. ¿Cómo resolvería este error?
snapshot.value
tiene el tipo Any?
, por lo que debe convertirlo al tipo subyacente antes de que pueda subíndices. Como snapshot.value!.dynamicType
es NSDictionary
, use un molde opcional as? NSDictionary
as? NSDictionary
para establecer el tipo, y luego puede acceder al valor en el diccionario:
if let dict = snapshot.value as? NSDictionary, postContent = dict["content"] as? String { content = postContent } else { content = "" }
O bien, puedes hacerlo como un trazador de líneas:
content = (snapshot.value as? NSDictionary)?["content"] as? String ?? ""
También tengo un código que te permite acceder a los valores de los nodos secundarios. Espero que esto te ayude:
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) } } }
Saludos cordiales, Nazar Medeiros