2016-11-20 26 views
1

這裏是我的數據庫結構:火力地堡字典收益爲零時,顯然有數據

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

我試圖找回所有的訂單,但dictionary.value是零,雖然在印刷清晰字典包含的數據。

代碼:

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 
     }} 

輸出:

snapshot dictionarty name snapshot nil //*1 

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

回答

1

for循環,您使用的,t實際上是(key: String, value: AnyObject)類型的元組。要訪問實際的keyvalue,您只需分別執行t.keyt.value。由於t不是字典,因此無需再將字符串key傳遞給它。

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

哦,你知道它爲什麼是一個元組而不是字典嗎?令我困惑的是,我在不同的地方使用這段代碼(在重構數據庫之前),它返回了一個字典,這很容易,因爲它允許我在一個循環中提取所有數據,而不是這樣。 – user1883993

+0

它是一個元組,因爲你正在迭代字典..它就像當你有一個整數數組時。迭代它會給你實際的整數..當你遍歷字典;因爲它是一個鍵/值的配對,它由兩個屬性組成,這些屬性最好以一個元組的形式表示。如果你想以字典的形式訪問它,然後擺脫for循環..我發佈了一個有關這個的答案 - > https :// stack overflow.com/a/39862631 – eshirima

+0

謝謝你emil,你真的救了我幾個小時的頭痛。 – user1883993