SwiftUI .sheet Unexpectedly found nil while unwrapping an Optional value

The Problem

The following example highlights my issue better than I can explain it. I explicitly give an optional variable a value before presenting a sheet. This sheet, which requires a non-optional variable to init, doesn't register the value and says it is nil. I can't understand why this would be if I only ever call the sheet after the optional has been given a value. Any help would be greatly appreciated. Thanks!

What I have tried

In the example I replaced:

.sheet(isPresented: $showModalView, content: {
     EditBookView(book: editingBook!) //Fatal error here
})

with:

.sheet(isPresented: $showModalView, content: {
     if let book = editingBook {
         EditBookView(book: book)
     }
})

However, this just shows an empty sheet (implying that editingBook is empty). But, interestingly when I close this empty sheet and select another item in the list, the view appears as intended.

Reproducible example

import SwiftUI

struct Book: Identifiable {
    var id: UUID
    var title: String
    
    init(title: String){
        self.title = title
        self.id = UUID()
    }
}

struct ContentView: View {
    
    @State var books = [Book]()
    @State var showModalView = false
    
    @State var editingBook: Book? = nil
    
    var body: some View {
        List{
            ForEach(books){ book in
                VStack(alignment: .leading){
                    Text(book.title)
                            .font(Font.title.bold())
                    Text("id: \(book.id.uuidString)")
                        .foregroundColor(.gray)
                    Button(action: {
                        editingBook = book
                        showModalView = true
                    }){
                        Text("Edit")
                            .foregroundColor(.accentColor)
                    }
                    .buttonStyle(PlainButtonStyle())
                    .padding(.top)
                }
            }
        }
        .padding()
        .onAppear{
            for i in 0...50 {
                books.append(Book(title: "Book #\(i)"))
            }
        }
        .sheet(isPresented: $showModalView, content: {
            EditBookView(book: editingBook!) //Fatal error here
        })
    }
    
}

struct EditBookView: View {
    var book: Book
    
    var body: some View {
        Text(book.title)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Edit:

enum SheetChoice: Hashable, Identifiable {
    case addContentView
    case editContentView

    var id: SheetChoice { self }
}

...


.sheet(item: $sheetChoice){ item in
                        switch item {
                        case .addContentView:
                            AddContentView()
                                .environmentObject(model)
                        case .editContentView:
                            //if let selectedContent = selectedContent {
                                ContentEditorView(book: selectedContent!, editingFromDetailView: false)
                                    .environmentObject(model)
                            //}
                        }
}



Read more here: https://stackoverflow.com/questions/66262213/swiftui-sheet-unexpectedly-found-nil-while-unwrapping-an-optional-value

Content Attribution

This content was originally published by santi.gs at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: