-1

i want to retrive data from firebase. i was created a structure for user. but i am getting error in init method

Type 'Any' has no subscript members

struct userObj {
    var address:String!
    var name: String!
    var userId: String!
    var ref: DatabaseReference?
    var key: String!

    init(snapshot: DataSnapshot) {
        key = snapshot.key
        name = snapshot.value!["name"] as! String   // this line give error
        address = snapshot.value!["address"] as! String // this line give error
        userId = snapshot.value!["userId"] as! String // this line give error
        ref = snapshot.ref
    }
}

1 Answers1

1

DataSnapshot.value property is declared as var value: Any? { get }

It is not explicitly declared as dictionary type, but it may contain dictionary among other possible types

  • NSDictionary
  • NSArray
  • NSNumber (also includes booleans)
  • NSString

Before you can access dictionary (if you know there is one) you have to typecast it to get the actual dictionary you can use:

snapshot.value as? [String : AnyObject]

Please note that explicitly unwrapping optionals with ! will crash if there is no appropriate data of appropriate type.

Dalija Prasnikar
  • 27,212
  • 44
  • 82
  • 159