迭代通过字典,Firebase快照使用

时间:2017-10-06 10:05:25

标签: firebase for-loop swift3 firebase-realtime-database

我在迭代字典时遇到了问题。首先检查我的数据库database

这是我的代码

ref.child("Events").observe(.value, with: { (snapshot) in
    for child in snapshot.children{

        let snap = child as! DataSnapshot

        let valueSnap = snap.value as? [[String:Any]]
        let nombreEventDansClub = valueSnap?.count
        print(valueSnap)
        for index in 0...nombreEventDansClub!-1
        {
            print(valueSnap![index]["name"])
            //print(valueSnap![index]["end_time"])
            if(valueSnap![index]["end_time"] as? String == nil)
            {
                //do Something
            }
            else{
            let end_time_test = valueSnap![index]["end_time"] as? String
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
            dateFormatter.timeZone = TimeZone(abbreviation: "GMT+2:00")
            let end_test = dateFormatter.date(from: end_time_test!)!

恢复是完美的但是例如:如果事件-0-(3)不存在,应用程序会崩溃,我知道问题是我计算了事件的数量:事件 - (某事)并根据此迭代。我想知道是否有更聪明的方法。提前致谢

1 个答案:

答案 0 :(得分:0)

您可以通过以下方式解析快照: -

   ref.child("Events").observe(.value, with: { (snapshot) in
    guard let values = snapshot as? [Any] else { return }
    for value in values {
        guard let childrens = value as? [Any] else { continue }
        for children in childrens {
            guard let dict = children as? [String: Any] else { continue }
            for key in dict.allkeys {

                // TO debug all keys and values
                print(dict[key])
            }

            print(dict["description"] as? String)
            print(dict["end_time"] as? String)
            print(dict["id"] as? String)
            // other keys
        }
    }
}

强制解包可能会导致您的应用意外崩溃。