I'm trying to use "Realm" with a few lines of code found on "stackoverflow". I get an enigmatic compilation error: Generic parameter 'Element' could not be inferred on the line: let dogs = List<Dog>() every time I use List<> this error appears.
I've tried everything, cleaning up the build, quitting xcode, starting again from scratch with a new project, but there's still this error...
import SwiftUI
import RealmSwift
class Dog: Object {
@objc dynamic var name = ""
@objc dynamic var age = 0
}
class Person: Object {
@objc dynamic var name = ""
let dogs = List<Dog>()
}
struct ContentView: View {
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundStyle(.tint)
Text("toto")
.onAppear {
let myDog = Dog()
myDog.name = "Rex"
myDog.age = 5
hop(myDog: myDog)
}
}
.padding()
}
func hop(myDog: Dog) {
let realm = try! Realm()
let person = Person()
person.name = "Tim"
person.dogs.append(myDog)
try! realm.write {
realm.add(person)
}
}
}
Welcome to SO.
The first thing is intermixing @objc with Swift; there's no reason to do that (in fact, don't). Stick with Swift syntax as this point.
So the two Realm models should be this
The second thing is in the
.onAppearfunction - whenever .onAppear is called, a dog object will be instantiated, a person object will be instantiated and both will be written to Realm. The end result over time is you'll have a database full of Tim's and Rex's and that's probably not what you want.Lastly, Realm has a number of other language features with SwiftUI. I suggest reviewing the Realm with SwiftUI Quickstart to familiarize yourself with some of the other features it has. Nothing wrong with your code in that respect but you can leverage SwiftUI in other ways as well.
*
RealmSwift.Listneeds to be implicitly used here to avoid a name collision with SwiftUI'sList.