Search code examples
swiftswiftuicrashwidgetnsuserdefaults

Crash when getting value from shared Userdefaults


I use shared Userdefaults to get values from the parent iOS app into the iOS14 Widget extension. Everything seems to work, I never seen a crash, not sure if a widget could crash anyways, however, crash analytics say:

Swift runtime failure: Unexpectedly found nil while unwrapping an Optical value.

The line is where I get my value from shared Userdefault, so the last line from the following code:

struct QuitSmokingWidgetEntryView : View {
var entry: Provider.Entry

let myString:String = UserDefaults(suiteName: "group.com.xxx.xxx.widgetsharing")?.value(forKey: "myKey") as! String

As I said, everything seems to work without crashing, but what am I doing wrong that Xcode crash analytics tells me that many crashes happen in that line? How to fix that?

Thanks for help !


Solution

  • When force unwrapping with ! you always run the risk of a crash if the value is nil (or with as! if the cast fails).

    In this case, you can do this:

    let myString:String = UserDefaults(suiteName: "group.com.xxx.xxx.widgetsharing")?.string(forKey: "myKey") ?? "Default value"
    

    Using string(forKey:) avoids the need for the cast to String and then the nil coalescing ?? lets you provide a default value if none is found in the UserDefaults.