cosmos cosmos - 24 days ago 15
Swift Question

Append Json Data To Array - Firebase/Swift

I am trying to append data from Firebase to a variable called

var itemNumbers: [[String: AnyObject]]!
that belongs to an NSObject. This is how the fetch looks like:

let orderItems = snapDict["itemNumbers"] as! [String:String]
self.NSOBJECT.itemNumbers.append(orderItems as [String : AnyObject])
print(orderItems)


When I do this the app breaks exactly where I try to append orderItems to the array. This is my error:

fatal error: unexpectedly found nil while unwrapping an Optional value


JSON:

{ "order": {
"itemNumbers" : {
"1": "Item Description",
"2": "Item Description"
}
}
}


Do I need to convert orderItems into something else before I try to append it?

Thanks for the help!

Answer

mention comment

well if you want to append order then use [[String: AnyObject]] on the other hand append itemNumbers for [String:String]

      guard  let  itemNumbers= snapDict["itemNumbers"] as? [String:String]  else{
         return
     }

      self.NSOBJECT.itemNumbers.append(itemNumbers)

or

      guard  let  orderItems = snapDict["order"] as? [[String: AnyObject]]  else{
         return
     }

      self.NSOBJECT.itemNumbers.append(orderItems)

Note : avoid the problematic implicit conversion [[String: AnyObject]]!

Comments