Iterate ObservedResults and get Wrapper on items

Hi guys,

I hope someone can help me here.
I have a SwiftUI like this:

struct Home: View {
    
    @ObservedResults(RealmPet.self) var pets
    
    var body: some View {
        
        VStack {
            ForEach(pets, id: \.id) { pet in
...

Is there any way to get to the wrapper of pet like if it was a @ObservedRealmObject ?
Because I want to be able to do something like:

$pet.name = "newName"

(without needing to manually find the object from the realm first). I have quite a few places where I need to be able to modify values, and would like to keep it compact (like it would be with @ObserveredRealmObject).

I’d love to hear a solution to this.
Thanks in advance!

1 Like

Do you have any ideas now? same problem here.

@wangpeiyi0223

A couple of things on this.

If you know the object you want to manipulate then it would not need to “manually find the object from the realm” per the original question from 2022. And, based on the provided code you’d know that object.

Here’s an example. Suppose there’s a simple list of dogs, and for any dog name clicked, change it to JayDog

@ObservedResults(NameModel.self) var nameList

List(dogList, id: \.self, selection: $selection) { dog in
    Text(dog.name)
    .onTapGesture {
        let thawedDogRealm = dog.thaw()!.realm!
        let thawedDog = dog.thaw()!
        try! thawedDogRealm.write {
            thawedDog.name = "JayDog"
        }
    }
}

No fetching required - just keep in mind that with SwiftUI, the wrappers work with frozen objects so they need to be thawed to manipulate them.

1 Like