Firebase and Swift

Hello! Per request of a friendly reddit user, I’m going to be doing a quick tutorial on using firebase with swift and how to structure your data models. Before we do anything, just a quick disclaimer, this tutorial is in swift 3, which, even though my life would be made much easier had I used swift 4 (google codeable swift 4), is the current default.

For the most part every firebase item we’ll have will have an ID and a name. Very simply, every item we construct needs to be able to produce a JSON object, and must be able to be constructed from a firebase item.

Following Firebase’s standards we’re going to avoid nesting our data, and keep it very simple.

Now automatically, every time an item is added or removed from our database the tableview will automatically reload. For a small application like this, this pattern is perfect; very extendable and very easy to understand. Now let’s see how easy it is to add a new item.

As you can see it’s incredibely easy to implement this if you wanted to create a new class. What’s also useful is that there are no strong ties to firebase from the table view. Please let me know what you think on reddit!

If you have json within json, as long as that piece of data implements the FirebaseItem protocol, all you have to do is call the getJSON() method. Because of the type system, this simple approach allows us to do whatever we want. What’s also great about this is that if you have a sub model that then has another object within it, all you have to do is call that item’s getJSON() method within that sub-model’s method.