2017-03-15 40 views
-1

enter image description here
我試圖將緊急數據解析爲緊急結構,但它從來沒有定性條件,並進入其他case.Here是我的代碼和結構。我寫了一些woring在第一行。正在解析swift3中的問題

if let emergencyDict = snapshotValue["emergency"] as? [String:[String:Any]]{ 
     for (emerId, emerData) in emergencyDict { 
      let emer = Emergency.init(emergency: emerData as NSDictionary) 
      emergency.append(emer) 
     } 
    } 
    else{ 
     let emer = Emergency.init(emerg: "" as AnyObject) 
     emergency.append(emer) 
    } 


struct Emergency{ 
var emer_id: String 
var emer_name: String 
var emer_phoneNo: String 

init(emergency: NSDictionary) { 

    if emergency.object(forKey: "id") != nil { 
     emer_id = emergency.object(forKey: "id") as! String 
    } 
    else{ 
     emer_id = "" 
    } 
    } 
} 

回答

1

您有emergency[Any]型數組,如果你刪除第一個問題對象然後你得到類型爲[[String:Any]]的數組。所以試試這樣。

if let array = snapshotValue["emergency"] as? [Any], 
    let emergencyArrar = Array(array.dropFirst()) as? [[String:Any]] { 

    print(emergencyArray) 
    for emergency in emergencyArray { 
     print(emergency) 
    } 
} 
0

你已經在這行寫的不對:

if let emergencyDict = snapshotValue["emergency"] as? [String:[String:Any]]{ 

它應該是:

if let emergencyDict = snapshotValue["emergency"] as? [[String:Any]]{ 
+0

我試過這個,但它也沒有奏效。 –

+0

當我試圖打印 打印(snapshotValue [ 「緊急」] ?? AnyObject.self) 則O/P爲: ( 「」, { ID = 1; 名稱=父親; PHONENO = 01828020209; },{ ID = 2; 名稱=母親; PHONENO = 12345678; } ) –

+0

'snapshotValue [ 「緊急」]'是一個數組正確? –

0

這個問題應該屬於從firebase數據庫查詢。

// you have to get the children in emergency, 
// then get the value(dictionary) of each child 
ref.child("emergency").observeSingleEvent(of: .value, with: { (snapshot) in 
     let value = snapshot.value as? NSDictionary 
     let keys = value?.allKeys // [1, 2, 3 ....] 

     for key in keys { 
      ref.child("emergency").child(key)..observeSingleEvent(of: .value, with: { (snapshot) in 
       let value = snapshot.value as? NSDictionary 
       // Here is your dictionary 
      } 
     } 


    }) { (error) in 
     print(error.localizedDescription) 
    }