Rory Rozzer Hodgson
Rory Rozzer Hodgson

Reputation: 69

Loop through Firebase database and assign values to variables

I have a Firebase database that contains data about events and their physical locations. I am trying to loop through the whole database and display them on a map. I can't figure out I would go about doing this. How can I create a lot of variables without actually manually creating them?

Please see the below code as to how I am trying to do it now (and failing).

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

Upvotes: 0

Views: 142

Answers (1)

Robin Stewart
Robin Stewart

Reputation: 3883

You can create an array of tuples, with each tuple holding one record of data. This would replace your class variables for eventTitleAnnotation2, eventLocationAnnotation2, etc:

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

Then, inside your loop, you can create tuples for each record and add them to the array as you go:

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)

Even better, you could unwrap all of your optionals in an if-let to safely avoid any unforeseen issues with the incoming data:

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

Later you can access your data as you would with any array, for example:

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

Or you can pull out individual columns with map():

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

I've found this to be a convenient approach for handling small datasets in Swift.

Upvotes: 2

Related Questions