Firebase Accessing Snapshot Value Error in Swift 3

2019-04-30 05:01发布

I recently upgraded to swift 3 and have been getting an error when trying to access certain things from a snapshot observe event value.

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

2条回答
smile是对你的礼貌
2楼-- · 2019-04-30 05:23

When Firebase returns data, snapshot.value is of type 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.

Since we know that Firebase Database uses a JSON-tree; pretty much key/value pairing, then you need to cast your snapshot.value to a dictionary as shown below.

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
    }
}
查看更多
The star\"
3楼-- · 2019-04-30 05:41

I think that you probably need to cast your snapshot.value as a 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

查看更多
登录 后发表回答