简体   繁体   中英

What is the right way to present data from Realm in SwiftUI List

I'm trying to fetch all of the items from Realm and display them in a SwiftUI List but I keep getting an error.

In a UIKit/Realm application, I would just create a Results variable to store all of the items from Realm then, I would fetch items in the viewDidLoad method and assign them to the variable. I'm trying to do the same thing in SwiftUI but I'm not sure how to structure my code, I keep getting an error saying that my Realm model should conform to the StringProtocol , I'm pretty sure this has to do with my lack of understanding Binding in SwiftUI .

Again, all I'm trying to do is fetch all of the items from Realm and display them in a SwiftUI List .

Here is what I have.

Realm Object:

class User:Object{
    @objc dynamic var name:String = ""
    @objc dynamic var age:Int = 0
    @objc dynamic var createdAt = NSDate()

    @objc dynamic var userID = UUID().uuidString
    override static func primaryKey() -> String? {
        return "userID"
    }
}

SwiftUI Code:

struct ContentView: View {
    @State private var allUsers : Results<User>!
    var body: some View {
        VStack{
            List{
                ForEach(allUsers, id:\.self) { user in
                    Text(user) // the error points here
                }
            }
        }.onAppear(){
            self.updateUserResults()
        }
    }
    func updateUserResults(){
        allUsers = realm.objects(User.self)
    }
}

Error:

Initializer 'init(_:)' requires that 'User' conform to 'StringProtocol'

What am I missing?

Probably you meant this

ForEach(allUsers, id:\.self) { user in
    Text(user.name)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM