#SwiftUI: Stop using AppStorage directly. It’s prone to typos, value mismatches and more.
Instead give yourself strongly typed keys and associated defaults, à la EnvironmentValues.
I’ve published my implementation as a package, but you can just as easily wrap AppStorage yourself with a few dozen lines.
@phill I’m doing almost the same by introducing a „TypedKey“, but added a buch of initializers to AppStorage. Upside: It’s as familiar as possible to anyone who knows AppStorage.
TypedKey is also used everywhere where having typed values and potentially default values makes sense. I strongly wonder why it’s not part of the system tbh.
@keval @gernot beware that even if with an optional value the store will always return a default value. Double will return 0 if there is no entry, Bool will return false, etc. This can have subtle and unexpected consequences if you’re expecting nil.
By clearly defining your default values you’re making your codebase easier to reason with, test, etc.
@gernot @keval the AppStorage interface will always return its default value, however if you access the value through the store (e.g UserDefaults.standard.double(forKey:)) you will get the store's default instead.
Yet another reason for having a common interface everywhere!
https://developer.apple.com/documentation/foundation/userdefaults/1416581-double
@phill @keval You sure?
@AppStorage("Test") private var test: Double?
is nil as it should be if it’s not set.
@AppStorage("Test2“) private var test2: Double? = 12.0
is 12.0 if it’s not set.
The self.init(wrappedValue:) in the initialisers jus just another form of writing the exact same thing.