我收到此错误:尝试运行此代码块时,“类型’Any’没有下标成员”:
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具有类型Any?,因此您需要将其强制转换为基础类型,然后才能对其进行下标。由于snapshot.value!.dynamicTypeis NSDictionary,请使用可选的强制as? NSDictionary类型转换来建立类型,然后您可以访问字典中的值:
snapshot.value
Any?
snapshot.value!.dynamicType
NSDictionary
as? NSDictionary
if let dict = snapshot.value as? NSDictionary, postContent = dict["content"] as? String { content = postContent } else { content = "" }
或者,您也可以单线执行此操作:
content = (snapshot.value as? NSDictionary)?["content"] as? String ?? ""