Realm with SwiftUI Tutorial: Getting Started | raywenderlich.com

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


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/32960966-realm-with-swiftui-tutorial-getting-started

Hi Renan,
What is the benefit of using an enum instead of a singleton for example for the RealmMigrator ?

Hi @chlorofom,
Great question! You want to use a Singleton for objects that you want to make sure they’ll only have a single instance in your code.

Since I’m setting the Realm.Configuration in the environment, and I’m not changing the configuration during runtime, I made a computed property for this object, making sure I can only get it to set the environment. Plus, this is a struct, so it’s pretty fast to instantiate should you need to use it again somewhere else.

A singleton would allocate memory for itself and be available during the duration of the app, but we’re only using this property to run the migration during the app launch, so there’s no actual need to keep an instance of the configuration.

I’m also using an enum because I want to make sure that there’s no way to instantiate a RealmMigrator. You’d only be able to access its static properties. If I did the same with a struct, you’d be able to instantiate RealmMigrator (and that makes no sense here).

Hope this helps you! :]

1 Like