You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI项目中Optional值强制解包触发致命错误排查及CreateView中@State变量使用合理性咨询

Fixing the Fatal Error & Addressing State Usage in Your SwiftUI App

Let's break down the solutions to your problems step by step:

1. Resolving the Unexpectedly found nil Fatal Error

The core issue here is force-unwrapping optional values that don't exist yet in UserDefaults. When your app runs for the first time, there are no saved values for "TitleInput" or "OptionInput", so UserDefaults.standard.string(forKey:) returns nil. Using ! to force unwrap this nil causes the crash.

Fix: Use Nil Coalescing for Default Values

Update your AppData initializer to provide a fallback value when no saved data exists:

init() {
    userData = [
        ShortcutViewModel(shortcut: Shortcut(title: "What for Dinner?", option: "Chinese")),
        ShortcutViewModel(shortcut: Shortcut(title: "What for Lunch?", option: "Pasta")),
        ShortcutViewModel(shortcut: Shortcut(title: "What for Breakfast?", option: "Toast"))
    ]
    // Replace force unwraps with nil coalescing
    self.showTitle = UserDefaults.standard.string(forKey: "TitleInput") ?? ""
    self.showOption = UserDefaults.standard.string(forKey: "OptionInput") ?? ""
}

This ensures if no saved value is found, the properties default to an empty string instead of crashing. The error markers in your App file will disappear automatically once this fix is applied, since the crash originated in AppData's init.

Bonus Fix: Remove Unused text Parameter in ContentView

Your ContentView struct doesn't declare a text property, but you're passing it in both the app entry and preview. This will cause a compile error. Fix it by either:

  • Removing the parameter from all calls:
    // In App file
    ContentView()
        .environmentObject(AppData())
    // In ContentView_Previews
    ContentView()
    

Or, if you intended to use the text property, add it to ContentView:

struct ContentView: View {
    @Binding var text: String // or @State var text = ""
    // Rest of your code
}

2. Is Using @State for titleInput2/optionInput2 Reasonable?

Absolutely! Using @State here is the correct approach.

  • @State is designed for local, mutable view state—exactly what these text fields need. They hold temporary user input specific to the CreateView instance until the user taps "Save".
  • Once the user saves, you correctly pass these values to your shared AppData model, which persists them to UserDefaults. This separation of temporary view state and persistent app data is a best practice in SwiftUI.

Optional Enhancement: Pre-fill Existing Values

If you want the CreateView to load the last saved values when it opens, add an .onAppear modifier to populate the state variables:

struct CreateView: View {
    // ... existing properties ...
    
    var body: some View {
        ZStack {
            // ... your view code ...
        }
        .onAppear {
            titleInput2 = appData.showTitle
            optionInput2 = appData.showOption
        }
    }
}

This lets users edit their previous input instead of starting from scratch.

内容的提问来源于stack exchange,提问作者Patrick Lee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 12:12:30