user1883993 user1883993 - 12 days ago 6
Swift Question

Firebase dictionary return nil when clearly has Data

Here is my database structure:

orders_Placed {
orderID {"date":...etc}
}


I'm trying to retrieve all orders, but the
dictionary.value
is nil although the dictionary when printed clearly contains data.

Code:

ref.child("orders_Placed").observe(.childAdded, with: { snapshot in

if let tes = snapshot.value as? Dictionary<String, AnyObject> {
print("snapshot dictionarty is snapshot \(tes.reversed())")
for t in tes {
print("\nsnapshot dictionarty name snapshot \(t.value["date"])") //*1

print("\nsnapshot dictionarty name key T IS \(t)") //*2
}}


Output:

snapshot dictionarty name snapshot nil //*1

snapshot dictionarty name key T IS ("date", 1479580695307) //*2 clearly has data but for some reason returns nil?

Answer

The for loop that you used, t is actually a tuple of type (key: String, value: AnyObject). To access the actual key or value, you simply have to do t.key or t.value respectively. No need to pass the string key to it anymore since t isn't a dictionary.

for t in tes
{
  var currentDateKey = t.key // the key associated to the date
  var currentDate = t.value // extracts the exact value
}
Comments