[英]Firebase Accessing Snapshot Value Error in Swift 3
I recently upgraded to swift 3 and have been getting an error when trying to access certain things from a snapshot observe event value. 我最近升级到swift 3,并且在尝试从快照观察事件值访问某些内容时遇到错误。
My code: 我的代码:
ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
let username = snapshot.value!["fullName"] as! String
let homeAddress = snapshot.value!["homeAddress"] as! [Double]
let email = snapshot.value!["email"] as! String
}
The error is around the three variables stated above and states: 错误是围绕上述三个变量并指出:
Type 'Any' has no subscript members 类型“任何”没有下标成员
Any help would be much appreciated 任何帮助将非常感激
I think that you probably need to cast your snapshot.value
as a NSDictionary
. 我认为您可能需要将
snapshot.value
为NSDictionary
。
ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
let username = value?["fullName"] as? String ?? ""
let homeAddress = value?["homeAddress"] as? [Double] ?? []
let email = value?["email"] as? String ?? ""
}
You can take a look on firebase documentation: https://firebase.google.com/docs/database/ios/read-and-write 您可以查看firebase文档: https : //firebase.google.com/docs/database/ios/read-and-write
When Firebase returns data, snapshot.value
is of type Any?
当Firebase返回数据时,
snapshot.value
的类型为Any?
so as you as the developer can choose to cast it to whatever data type you desire. 因此,开发人员可以选择将其转换为您想要的任何数据类型。 This means that
snapshot.value
can be anything from a simple Int to even function types. 这意味着
snapshot.value
可以是从简单的Int到偶数函数类型的任何东西。
Since we know that Firebase Database uses a JSON-tree; 因为我们知道Firebase数据库使用JSON树; pretty much key/value pairing, then you need to cast your
snapshot.value
to a dictionary as shown below. 几乎是键/值配对,然后你需要将
snapshot.value
转换为字典,如下所示。
ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
if let firebaseDic = snapshot.value as? [String: AnyObject] // unwrap it since its an optional
{
let username = firebaseDic["fullName"] as! String
let homeAddress = firebaseDic["homeAddress"] as! [Double]
let email = firebaseDic["email"] as! String
}
else
{
print("Error retrieving FrB data") // snapshot value is nil
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.