Search code examples
swiftmodal-dialogrealmactionswipe

RealmSwift: SwipeAction to show edit modal


I'm trying a List with lessons with a SwipeAction to show an edit modal:

@ObservedResults(Lesson.self) var lesson

@State private var showEditModal = false
@State private var forEdit: Lesson?    

NavigationStack {
   List {
      ForEach(lessons) { lesson in
         NavigationLink(destination: LessonView(selectedLesson: lesson)) {
            Text("\(lesson.name)")
         }
         .swipeActions(allowsFullSwipe: false) {                           
            Button {
               forEdit = lesson
               showEditModal = true
            } label: {
               Label("Edit", systemImage: "pencil")
            }
            .tint(.blue)
         }
      }
   }
   .navigationTitle(title)
}
.sheet(isPresented: $showEditModal) {
   NavigationStack {
      EditLesson(showModal: $showEditModal, lesson: forEdit!)
   }
   .interactiveDismissDisabled()
}

In the view EditLesson there is @Binding var showModal: Bool and @ObservedRealmObject var lesson: Lesson.

After building and then testing I get the following error:

Fatal error: Unexpectedly found nil while unwrapping an Optional value

I've tried a lot of variants, but didn't find a solution yet. Can you help me, please? Thanks in advance!


Solution

  • It was my mistake. I tried the solution before, but made a syntax error:

    • in .swipeActions:

      Button { editLesson(lesson: lesson) } label: { Label("Edit", systemImage: "pencil") }

    • the called function:

      func editLesson(lesson: Lesson) { forEdit = lesson }

    • the sheet:

      .sheet(item: $forEdit) { editLesson in NavigationStack { EditLesson(lesson: editLesson).environmentObject(realmService) } }

    Now it works without any problems. I forgot editLesson in inside the sheet syntax. Thank you for your comment.