I use the @AppStorage to save some preference in the settings view, just like apple recommends: https://developer.apple.com/documentation/swiftui/settings
I also have a main window and it will read some preference before user open the settings view and then it seems I will read "wrong" UserDefaults because the expect values are not write to UserDefaults because the settings view is not loaded yet.
For example:
// Settings view
struct SettingsView: View {
@AppStorage("x") var x = 5 // give preference a default value
...
}
// Main view
struct MainView: View {
func foo() {
let x = UserDefaults.standard.double(forKey: "x")
// x is not the default value I expect
}
}
Possible solutions I know:
- On app launch, check if the UserDefaults is nil, if so then write them with default values
- When read UserDefaults, check if UserDefaults is nil, if so then read the default values instead.
Are there any better ways to handle it? Thanks!