Home > other >  SwiftUI: Unexpectedly found nil while unwrapping an Optional value
SwiftUI: Unexpectedly found nil while unwrapping an Optional value

Time:11-20

I am following Stanford's CS193p Developing Apps for iOS online course. I'm trying to do the Assignment 6 (Memorize Themes.pdf).

When I run my app in simulator and in edit mode tap on a list row to bring up the sheet, I get the following fatal error: Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

Question: Why the index matching themeToEdit inside themes array is nil?

Please help me.

import SwiftUI

// Required Task 3: Your Memorize application should now show a “theme chooser” UI when it launches.

struct ThemeChooserView: View {
    @EnvironmentObject var themeStore: ThemeStore
    
    @State private var editMode: EditMode = .inactive
        
    var body: some View {
        NavigationView {
            List {
                ForEach(themeStore.themes) { theme in
                    NavigationLink(destination: EmojiMemoryGameView(game: EmojiMemoryGame(theme: theme))) {
                        VStack(alignment: .leading) {
                            Text(theme.name)
                                .foregroundColor(theme.color)
                                .font(.title)
                            Text(themeCardsDescription(theme: theme))
                        }
                        .gesture(editMode == .active ? tapGesture(theme: theme) : nil)
                    }
                }
                .onDelete { indexSet in
                    themeStore.themes.remove(atOffsets: indexSet)
                }
                .onMove { indexSet, newOffset in
                    themeStore.themes.move(fromOffsets: indexSet, toOffset: newOffset)
                }
            }
            .sheet(isPresented: $isEditing) {
                let currentThemeIndex = themeStore.themes.firstIndex(where: {$0.id == themeToEdit?.id})
                ThemeEditor(theme: $themeStore.themes[currentThemeIndex!]) // ERROR: -            
  • Related