遍历Firebase数据库并将值分配给变量

时间:2018-07-09 21:03:39

标签: ios swift firebase mapkit

我有一个Firebase数据库,其中包含有关事件及其物理位置的数据。我试图遍历整个数据库并将它们显示在地图上。我不知道我会去做。如何在不手动创建变量的情况下创建大量变量?

请参阅下面的代码,以了解我现在(以及失败)的尝试方式。

eventItemReference.observe(.value, with: { DataSnapshot in
    for child in DataSnapshot.children.allObjects as! [DataSnapshot] {
        let valuess = DataSnapshot.value as? [String : AnyObject]
        print("printed the child value",child.value!)
        self.eventTitleAnnotation2 = (valuess!["Event Title"] as? String)!
        self.eventLocationAnnotation2 = (valuess!["Event Location"] as? String)!
        self.eventLatAnnotation2 = (valuess!["Event latitude"] as? CLLocationDegrees)!
        self.eventLongAnnotation2 = (valuess!["Event Longitude"] as? CLLocationDegrees)!

1 个答案:

答案 0 :(得分:2)

您可以创建一个元组数组,每个元组保存一个数据记录。这将替换您的类变量,用于eventTitleAnnotation2,eventLocationAnnotation2等:

var events = [(title:String, location:String, lat:CLLocationDegrees, long: CLLocationDegrees)]()

然后,在循环内,您可以为每个记录创建元组,然后将它们添加到数组中:

let event = (title: (valuess!["Event Title"] as? String)!,
             location: (valuess!["Event Location"] as? String)!,
             lat: (valuess!["Event latitude"] as? CLLocationDegrees)!,
             long: (valuess!["Event Longitude"] as? CLLocationDegrees)!
            )
events.append(event)

更好的是,您可以将所有可选选项都包装在if-let中,以安全地避免传入数据出现任何不可预见的问题:

if let title = valuess!["Event Longitude"] as? CLLocationDegrees,
   let location = valuess!["Event Location"] as? String,
   let lat = valuess!["Event latitude"] as? CLLocationDegrees,
   let long = valuess!["Event Longitude"] as? CLLocationDegrees
{
    let event = (title:title, location:location, lat:lat, long:long)
    events.append(event)
}

之后,您可以像访问任何数组一样访问数据,例如:

for event in self.events {
    someViewString = event.title
    // etc
}

或者您可以使用map()提取单个列:

let allTitles:[String] = self.events.map{ $0.title }

我发现这是在Swift中处理小型数据集的便捷方法。