简体   繁体   中英

how can i get array from child and save in struct from firebase in swift

I have a fast question that i not found exactly here.

I have a struct that save all data from my firebase user. The problem is that my user have an dynamic list, always can be 0, or have 3 or more lines of type [String:Int], in resume i think a_trips is [[String:Int]]

my actual struct:

struct User {

let fullname: String
let location: String
let uid: String

let a_trips: ? 

    
init(uid: String, dictionary: [String: Any]) {
    
    self.uid = uid
    self.fullname = dictionary["fullname"] as? String ?? ""
    self.location = dictionary["location"] as? String ?? ""
    
    // i dont know to get array of array of a_trips here
    

    
}

}

example of user in firebase:

id:{

   uid:{
      
      fullname: "name",
      uid: "121948349238",
      location: "example location",
      a_trips: {
         "trip1": {
            id: 1432542543 (int)
         },
         "trip2": {
            id: 1523524654 (int)
         }
         ...
      }

   }

}

or... sometimes can be:

id:{

   uid:{
      
      fullname: "name",
      uid: "121948349238",
      location: "example location",
      a_trips: {
        // nil
      }

   }

}

Solved. Thanks so much all. I could find the solution

struct User {

 let fullname: String
 let location: String
 let uid: String

 
 // i finally create a simple array
 var tripList: [Int]

    
 init(uid: String, dictionary: [String: Any]) {
    
    self.uid = uid
    self.fullname = dictionary["fullname"] as? String ?? ""
    self.location = dictionary["location"] as? String ?? ""
    
    var arrayTripsAux = [Int]()
    if let a_trips = dictionary["a_trips"] as? [String: [String:Int]]{
        
        for t in a_trips.values{
            arrayTripsAux.append(t["id"] ?? 0)
        }
        
    } else {
        arrayTripsAux.append(0)
    }
    
    // return childs in array
    self.tripList = arrayTripsAux
    

    
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM