My data structure looks like this below with a document containing some fields and an array of "business hours":
The parent struct looks like this:
protocol RestaurantSerializable {
init?(dictionary:[String:Any], restaurantId : String)
}
struct Restaurant {
var distance: Double
var distributionType : Int
var businessHours : Array<BusinessHours>
var dictionary: [String: Any] {
return [
"distance": distance,
"distributionType": distributionType,
"businessHours": businessHours.map({$0.dictionary})
]
}
}
extension Restaurant : RestaurantSerializable {
init?(dictionary: [String : Any], restaurantId: String) {
guard let distance = dictionary["distance"] as? Double,
let distributionType = dictionary["distributionType"] as? Int,
let businessHours = dictionary["businessHours"] as? Array<BusinessHours>
else { return nil }
self.init(distance: distance, geoPoint: geoPoint, distributionType: distributionType, businessHours, restaurantId : restaurantId)
}
}
And here is the business hours struct:
protocol BusinessHoursSerializable {
init?(dictionary:[String:Any])
}
struct BusinessHours : Codable {
var selected : Bool
var thisDay : String
var startHour : Int
var closeHour : Int
var dictionary : [String : Any] {
return [
"selected" : selected,
"thisDay" : thisDay,
"startHour" : startHour,
"closeHour" : closeHour
]
}
}
extension BusinessHours : BusinessHoursSerializable {
init?(dictionary : [String : Any]) {
guard let selected = dictionary["selected"] as? Bool,
let thisDay = dictionary["thisDay"] as? String,
let startHour = dictionary["startHour"] as? Int,
let closeHour = dictionary["closeHour"] as? Int
else { return nil }
self.init(selected: selected, thisDay: thisDay, startHour: startHour, closeHour: closeHour)
}
}
I am trying to query the DB as such:
db.whereField("users", arrayContains: userId).getDocuments() { documentSnapshot, error in
if let error = error {
completion([], error.localizedDescription)
} else {
restaurantArray.append(contentsOf: (documentSnapshot?.documents.compactMap({ (restaurantDocument) -> Restaurant in
Restaurant(dictionary: restaurantDocument.data(), restaurantId: restaurantDocument.documentID)!
}))!)
}
And even though I have data, I keep getting this error on the last line above:
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
If I put a default value then all I get is the default value. How do I get the array of objects from the flat JSON?
I tried to obtain each individual field. And then parse through the business hours field but that seems inefficient. Any idea what I am doing wrong here?