SwiftUI #Previews: How to populate with data

Suppose you have a view:

struct Library: View {
    @State var books = []
    var body: some View {
          VStack {
             ...

            Button("add Book") {
                 ....
           }
       
    }
}

Such that Library view holds a Book array that gets populated internally via a button that opens a modal – or something alike.

How can I use #Peviews to preview Library with a pre-populated collection? Suppose I have a static books – dummy – array in my code just for that; still, what's the best way to use that to preview the Library view?

You do not show what books are. I suppose they are an array of some struct Book.

Not sure I fully understand your question.

But you can pass a books array to the Preview:

#Preview {
    Library(books: [populate an array of Book])
}
struct Book: Hashable {
    let name: String
    
    static let preview = [
        Book(name: "1"),
        Book(name: "2"),
        Book(name: "3")
    ]
}

struct Library: View {
    @State var books: [Book] = []
    @State private var isShowingSheet = false
    
    var body: some View {
        VStack {
            
            ForEach(books, id: \.self) { book in
                Text(book.name)
            }
            
            Button("add Book") {
                isShowingSheet = true
            }
        }
        .sheet(isPresented: $isShowingSheet) {
            Button("Add Book") {
                books.append(Book(name: "example"))
            }
        }
    }
}

#Preview {
    Library(books: Book.preview)
}

That works

You might also want to checkout Previewing your app’s interface in Xcode for examples on how to make complex objects reusable with a preview modifier

SwiftUI #Previews: How to populate with data
 
 
Q