Better Programming

Advice for programmers.

Follow publication

Member-only story

How To Create a Generic Backend Firebase API in Swift

Osaretin Idele
Better Programming
Published in
7 min readMay 18, 2021
cactus in a pot
Photo by Annie Spratt on Unsplash

One common approach while developing an iOS app based on Swift with a Firebase backend is to create a repository class that handles the tasks of creating, reading, updating, and deleting (CRUD) objects to the Firebase Firestore repository from your app. Typically, the repository class is updated anytime a new type is introduced to your app and all the CRUD operations are implemented for the new type. Most of these new implementations are boilerplate code base which is repeated across different type implementations.

A better approach to handle this situation might be to use Swift generics to create a base backend class that can handle any future classes created that adhere to a specified protocol without the need to duplicate repository implementation for the new type.

This article provides a workable minimal code approach to implement Firebase backend operations that can be plugged into any new or existing iOS project. This article also uses Swift reflection to implement a means of handling object primary keys when saving custom objects as Firebase documents.

Introduction

In this article, we will develop an iOS demonstration app with a backend API that will perform and demonstrate the following tasks:

  • Save a new object to a Firebase Firestore repository. The method will generate a documentID from Firebase and use this id as the object’s unique key and also as the name of the saved document. To do this, we need to be able to query the properties of any type and the data for the properties of an instance of the class at runtime. To achieve this, we make use of Swift reflection.
  • Retrieve a saved object from the Firestore repository by providing a unique primary key
  • Retrieve an array of objects based on a supplied condition by field and field value
  • Update an already existing object in the repository
  • Remove an existing object based on a unique primary key from the repository

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Osaretin Idele
Osaretin Idele

Written by Osaretin Idele

Software engineer, with special love for anything object based, Java, C#, Swift, JavaScript

No responses yet

Write a response