types“任何”没有下标成员(firebase)

我得到这个错误:“types”任何'没有下标成员“试图运行这段代码时:

init(snapshot: FIRDataSnapshot) { key = snapshot.key itemRef = snapshot.ref if let postContent = snapshot.value!["content"] as? String { // error content = postContent } else { content = "" } } 

我一直在寻找答案,并找不到一个解决这个问题与FireBase。 我将如何解决这个错误?

snapshot.value的types是Any? ,所以你需要将它转换为底层types,然后才能下标。 由于snapshot.value!.dynamicTypeNSDictionary ,请使用可选的cast as? NSDictionary as? NSDictionarybuild立types,然后你可以访问字典中的值:

 if let dict = snapshot.value as? NSDictionary, postContent = dict["content"] as? String { content = postContent } else { content = "" } 

或者,你可以把它作为一个单行的:

 content = (snapshot.value as? NSDictionary)?["content"] as? String ?? "" 

我也有一个代码,它允许你访问子节点的值。 我希望这可以帮助你:

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

最好的问候,Nazar Medeiros