How to use MongoDB realm with SwiftUI
MongoDB Realm

Realm is an open-source mobile database and is considered an alternative to CoreData and SQLite.
However, Realm was acquired by MongoDB and renamed MongoDB Realm. Developers can now seamlessly sync data from Realm to the MongoDB compass and Atlas without any hassle.
Pre-requisites
Install
Set up Swift app
-
Create a SwiftUI project with Xcode.
-
Open your project, go to
File>Swift Packages, and chooseAdd Package Dependency. -
Add the following URL:
https://github.com/realm/realm-cocoa, and hit Enter. -
Choose
RealmandRealmDatabaseand add them to your project.
Simple CRUD on Swift app
- Open
ContentView.swift, and importRealmSwift.
import SwiftUI
import RealmSwift
init(){
let realm = try! Realm()
print(Realm.Configuration.defaultConfiguration.fileURL!)
}
struct ContentView: View {
var body: some View {
Text("Hello, World!")
}
}
-
Realm.Configuration.default configuration.fileURL!will print the location ofdefault.realm, which is the local location of your Realm Database. -
Open this
default.realmfile using Realm Studio. It will be empty now, but we will see some data once we add it. -
Create a
structCars and add the following parameters:
struct Cars: Object {
@objc dynamic var name: String?
@objc dynamic var color: String?
}
@objcis added to view the variables from Objective C. Objective C is used to develop and create Realm Cocoa. That is why we add the@objckeyword.
- Now, initialize your
Carsobject and add some data into thenameandcolorparameters.
var cars = Cars()
cars.name = "Ferrari"
cars.color = "Red"
- Let’s add this to our Realm Database now:
try! realm.write {
realm.data(cars)
}
- Now, if you run the app, you’ll find a class named
Cars, with attributesnameandcolorwith valuesFerrariandRed, respectively. Similarly, you can tap into the properties ofCarsand then assign values to add more data.
Let’s retrieve some data from our Realm Database
let results = realm.objects(Cars.self)
print(results)
You can now see your results in a JSON Format.
If you want to take a parameter, say color, and you will be able to print it as:
print(results[0].color)
You can also create a filter to get a list of objects with the same property.
For example, if you want to get a list of all cars whose color is red, then you can say:
let redCars = realm.objects(Cars.self).filter("color = 'red'")
print(redCars)
Let’s delete some objects
try! realm.write {
realm.delete(cars)
}
If you want to delete only certain objects, you can filter the values and then delete them.
For example, let’s say you want to delete all the green colored cars:
try! realm.write {
let greenCars = realm.objects(Cars.self).filter("color = 'green'")
realm.delete(greenCars)
}
To learn more about CRUD operations and others from Realm with Swift, check out
. Realm Documentation for iOS SDK https://www.mongodb.com/docs/realm/sdk/ios/