Realm With SwiftUI Tutorial: Getting Started

Learn how to use Realm with SwiftUI as a data persistence solution by building a potion shopping list app. By Renan Benatti Dias.

5 (5) · 3 Reviews

Download materials
Save for later
Share
Update note: Renan Dias updated this tutorial for iOS 15, Swift 5.5 and Xcode 13. He also wrote the original version.

Realm Mobile Database is a popular object database management system. It’s open-source, and you can use it on multiple platforms. Realm aims to be a fast, performant, flexible and simple solution for persisting data while writing type-safe Swift code.

SwiftUI is Apple’s latest and hottest UI framework. It uses a declarative syntax to build your views using Swift code. It relies on states to reactively update its views when the user interacts with it. Because Realm uses Live Objects that also update automatically, mixing both frameworks just makes sense!

In this SwiftUI Realm tutorial, you’ll learn how to:

  • Set up Realm
  • Define data models
  • Perform basic CRUD operations on objects
  • Propagate changes from the database to the UI
  • Handle migrations when your data model changes

You’ll learn all this by implementing a Realm database in an app that tracks all the ingredients you need to make magic potions! So grab your potions kit because it’s time to dive right into this cauldron. :]

Note: This SwiftUI Realm tutorial assumes you’re familiar with SwiftUI. If you’re just getting started with SwiftUI, check out the SwiftUI Fundamentals video course or the SwiftUI by Tutorials book.

Getting Started

Download the project materials by clicking the Download Materials button at the top or bottom of this tutorial. Open PotionsMaster.xcodeproj inside the starter folder.

PotionsMaster is an app built for all your potion-making needs. Potion brewing is a challenging skill. Stirring techniques, timing and bottling can be arduous, even for experienced wizards. This app helps you track the ingredients you need and those you’ve already bought. With PotionsMaster, even that difficult new potion you’ve been reading about will be a snap!

It’s time to get to work. To start, build and run.

List with ingredients and bought ingredients

PotionsMaster is a simple app that lets you add, update and delete ingredients in a list. But as you play around with the app, you’ll notice a small problem. No matter what you do, the app doesn’t persist your data! In fact, it doesn’t perform any actions when you try to create, update or delete an ingredient. But don’t worry — you’re about to make it work using Realm.

Project Structure

Before you dive in and fix the app so you can start brewing your next potion, take a close look at the starter project. It contains the following key files:

  • Ingredient.swift: This class is a representation of an ingredient.
  • IngredientListView.swift: This is the main view of the app. It displays a List. There’s one Section for ingredients to buy and another for bought ingredients.
  • IngredientRow.swift: This is the row view for each ingredient in the list.
  • IngredientFormView.swift: You’ll use this Form to create and update ingredients.

Right now, IngredientListView has two arrays of ingredients: one for those ingredients you need to buy and another for those you’ve already bought. However, when the user interacts with the app, nothing happens. You can’t add, delete or update any ingredient. Those are just mock ingredients.

You’ll fix this by adding Realm to the project and building a basic CRUD with it. But before you do that, it’s important to understand what Realm is.

Working With Realm

Realm was built to provide a database persistence and data query framework with a native, familiar-to-read language syntax. For iOS, iPadOS, watchOS and macOS, data objects are defined using Swift classes rather than from a separate database schema like Core Data. It’s also available for many other platforms, including but not limited to:

  • Swift/Objective-C
  • Java/Kotlin
  • JavaScript
  • .NET
  • Dart

The coolest part about Realm is that the skills are transferable. Once you learn the Realm basics in one language, they’re easy to pick up in another language. And because Realm is a cross-platform database, its APIs don’t change much from one language to the next.

Still, Realm isn’t an all-purpose database. Unlike SQLite, Realm is a NoSQL object database. Like any other NoSQL database, it has advantages and disadvantages. But Realm is a great alternative for keeping multi-platform teams in sync.

Understanding the Realm Database

Before you set up Realm, you need to understand how it works.

Realm uses files to save and manage your database. Each Realm database in your app is called a realm. Your app might have multiple realms, each handling a different domain of objects. That helps keep your database organized and concise in your app. And because it’s available across platforms, you can share pre-loaded Realm files between platforms like iOS and Android. That’s really helpful, right? :]

To open a Realm file, you simply instantiate a new Realm object. If you don’t pass a custom file path, Realm creates a default.realm file in the Documents folder on iOS.

Sometimes you might want to use a realm without writing data on disk. The database provides a handy solution for these situations: in-memory realms. These can be useful when writing unit tests. You can use in-memory realms to pre-load, modify and delete data for each test case without writing on disk.

Realm Mobile Database isn’t the only product Realm provides. The company also offers Realm Sync, a solution for synchronizing Realm databases across multiple devices and in the cloud. Additionally, Realm provides a great app to open, edit and manage your databases: Realm Studio.

Setting up Realm

To start using Realm, you must include it as a dependency in your project. There are many dependency management tools you can use for this, such as the Swift Package Manager and CocoaPods. This tutorial uses Swift Package Manager, but feel free to use the tool you’re more comfortable with.

Note: If you’re not familiar with Swift Package Manager or want to learn more about it, check out Swift Package Manager for iOS tutorial.

To set up your dependency, select File ▸ Add Packages….

SPM window with a list of packages

Copy the following and paste into the combined search/input box:

https://github.com/realm/realm-swift

This is the location of the GitHub repository containing the Realm package.

Select the Realm-Swift package and select Up to Next Major Version under dependency rule. Next, leave the version as 10.25.0. This makes sure your project will use the latest version of Realm. (As of writing this is therefore from 10.25.0.) Finally, click Add Package.

SPM window with Realm Swift package selected

Next, select both Package Products — Realm and RealmSwift — and click Add Package.

SPM window with Realm products selected

Xcode downloads the code from the repository and adds the Realm package to the PotionsMaster target.

Build and run to be sure everything is working.

List with ingredients and bought ingredients

Now that you’ve set up Realm, you’re ready to create your first object model.