Binding with ForEach or List doesn't work anymore when using @Observable macro

Hi. The binding in a ForEach or List view doesn't work anymore when using the @Observable macro to create the observable object. For example, the following are the modifications I introduced to the Apple's example called "Migrating from the Observable Object Protocol to the Observable Macro" https://developer.apple.com/documentation/swiftui/migrating-from-the-observable-object-protocol-to-the-observable-macro


struct LibraryView: View {
    @Environment(Library.self) private var library
    
    var body: some View {
        List($library.books) { $book in
            BookView(book: book)
        }
    }
}

All I did was to add the $ to turn the reference to library.books into a binding but I got the error "Cannot find '$library' in scope"

Is this a bug or the procedure to use binding in lists changed?

Thanks

To get bindings from an Observable class, you need to use the @Bindable property wrapper as normal. However, the bindable value is coming from the environment so this is different.

Whether this solution is a workaround or the intention going forward, it works nonetheless.

var body: some View {
    @Bindable var library = library // place in view body

    List($library.books) { $book in
        BookView(book: book)
    }
}

At the moment, @Environment can't use for Binding

I don't know whether it's a bug or not

https://developer.apple.com/forums/thread/732658

Binding is for structs since you have an object it is just:

struct LibraryView: View {
    @Environment(Library.self) private var library
    
    var body: some View {
        List(library.books) { book in
            BookView(book: book)
        }
    }
}

Note there are 2 design flaws with your code:

  1. You shouldn't name your views with model types.
  2. Only pass the data the view needs not the whole object, e.g. it could be something like this:
    var body: some View {
        List(library.books) { book in
            BigView(topText: book.title, bottomText: "\(book.releaseDate, format: .date)")
        }
    }
Binding with ForEach or List doesn't work anymore when using @Observable macro
 
 
Q