Firebase Accessing Snapshot Value Error in Swift 3

血红的双手。 提交于 2019-12-22 06:59:23

问题


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


回答1:


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




回答2:


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
    }
}


来源:https://stackoverflow.com/questions/40567438/firebase-accessing-snapshot-value-error-in-swift-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!