Ios 类型';任何';没有Firebase的下标成员
我知道这个话题以前已经讨论过了,但是我还没有找到一个可以在我的代码中使用的StackOverflow解决方案。我可以做些什么来更新我的代码,使其在Swift 3上运行?我在Swift 2.2中没有这些错误 这是我如何格式化代码的:Ios 类型';任何';没有Firebase的下标成员,ios,swift,firebase,firebase-realtime-database,Ios,Swift,Firebase,Firebase Realtime Database,我知道这个话题以前已经讨论过了,但是我还没有找到一个可以在我的代码中使用的StackOverflow解决方案。我可以做些什么来更新我的代码,使其在Swift 3上运行?我在Swift 2.2中没有这些错误 这是我如何格式化代码的: import Foundation import Firebase import FirebaseDatabase import FirebaseStorage struct Comment { var image: String! var pos
import Foundation
import Firebase
import FirebaseDatabase
import FirebaseStorage
struct Comment {
var image: String!
var postID: String!
var description: String!
var username: String!
var price: String!
var rating: String!
var title: String!
var ref: FIRDatabaseReference?
var key: String!
init(postID: String, image: String, description: String, username: String, title: String, rating: String, price: String, key: String = ""){
self.description = description
self.postID = postID
self.username = username
self.title = title
self.rating = rating
self.price = price
self.image = image
self.ref = FIRDatabase.database().reference()
}
init(snapshot: FIRDataSnapshot){
self.description = snapshot.value!["description"] as! String // error here
self.postID = snapshot.value!["postID"] as! String // error here
self.title = snapshot.value!["title"] as! String // error here
self.rating = snapshot.value!["rating"] as! String // error here
self.price = snapshot.value!["price"] as! String // error here
self.image = snapshot.value!["image"] as! String // error here
self.key = snapshot.key
self.ref = snapshot.ref
}
func toAnyObject() -> [String: AnyObject] {
return ["image": image, "description": description , "username": username, "postId": postID, "title": title, "rating": rating, "price": price]
}
}
试试这个-:
init(snapshot: FIRDataSnapshot){
let keyValue = snapshot as! [String:Any]
for data in keyValue
{
// Get your values
}
}
以下代码应适用于您的情况:
init(snapshot: FIRDataSnapshot){
guard let values = snapshot.value as! [String: Any] else {
return
}
self.description = values["description"] as! String
self.postID = values["postID"] as! String
self.title = values["title"] as! String
self.rating = values["rating"] as! String
self.price = values["price"] as! String
self.image = values["image"] as! String
self.key = snapshot.key
self.ref = snapshot.ref
}
让我们知道您得到了什么。使用
let keyValue=snapshot.value as!Dictionary
,因为快照。value
声明为Any
@gabe您必须将Any类型强制转换为Swift Dictionary类型[String:AnyObject]。您的快照是Dictionary数组。@Sachin Vas谢谢。但是,我随后得到错误“无法将“Dictionary”类型的值赋给“String!”类型”<代码>让keyValue=snapshot.value为![String:String],如果您认为所有值都是String only,请使用上面的命令。@TusharSharma我仍然会遇到与条件绑定的[String:AnyObject]初始值设定项相同的错误强制转换,必须具有可选类型,而不是“[String:Any]”更改snapshot.value as![字符串:任意]
带有snapshot.value作为?[字符串:任意]
。这还需要将值[“…”]
更改为值[“…”]
或值![“…”]
。