Hi, I’m new to the MongoDB community with an interest in using MongoDB Realm with SwiftUI. Using some of the SwiftUI samples provided with Realm as guidance, I wanted to write an example of using Realm with the smallest amount of code. This is what I came up with (not even an HStack or padding to make it look nice):
import SwiftUI
import RealmSwift
class AutoMaker: Object, ObjectKeyIdentifiable {
@objc dynamic var name = ""
}
struct ContentView: View {
@State private var text = ""
@ObservedResults(AutoMaker.self) var autoMakers
var body: some View {
TextField("Automaker Name", text: $text)
Button(action: addItem) {
Text("Add")
}
List {
ForEach(autoMakers) {autoMaker in
Text(autoMaker.name)
}
.onDelete(perform: $autoMakers.remove)
}
}
func addItem() {
let maker = AutoMaker()
maker.name = text
$autoMakers.append(maker)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
And this is what it looks like:
It amazes me that I can create a working sample that adds and deletes items from a database with less than 20 lines of added code.
I do have a question however. In keeping with the theme of writing the smallest amount of code, if I want to add sample data to show up in the Preview window, what is the simplest way to do that? I found code in Andrew Morgan’s RChat example where there is a Realm.bootstrap() function called as the first line in PreviewProvider code (here). The function loads a realm database before the preview code is called. In that example, each Realm object class implements a protocol called Samplable in an extension and then provides sample data.
Is this the simplest way to test a SwiftUI view that uses Realm? Or is there a briefer way?
Thanks!
–Tom