我收到此错误:“尝试运行此代码块时,键入’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!.dynamicType是NSDictionary,使用可选的强制转换为? 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 ?? ""