ios - 遍历 Firebase 数据库并为变量赋值

标签 ios swift firebase mapkit

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

请看下面的代码,了解我现在是如何尝试做的(但失败了)。

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)!

最佳答案

您可以创建一个元组数组,每个元组保存一条数据记录。这将替换 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 中处理小型数据集的便捷方法。

关于ios - 遍历 Firebase 数据库并为变量赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51253997/

相关文章:

ios - 如何匹配水平 collectionView 单元格的宽度与其内容大小

ios - 核心数据问题 : There was an error creating or loading the application's saved data

json - Swift//将一个String Json文件转换为枚举大小写

ios - 将用户注册到 firebase 并登录(如果已注册)

javascript - function.querySnapshot 不是函数

ios - 移动到另一个屏幕时停止呈现 View Controller

ios - 苹果声称应用程序崩溃,但我无法弄清楚

ios - 如何更改缩短的后退按钮标题?

java - firebase 用户在第一次调用后每次都会返回 null

ios - Swift Play 视频无法显示