Ch. 10 @AppStorage use/style question

My first exposure to @AppStorage, so certainly willing to get schooled on this, but…

It strikes me as very poor form to declare and initialize the same variable multiple times in the same app. Kuchi has the following line in four different files.

@AppStorage("numberOfQuestions") var numberOfQuestions = 6

Seems awfully fragile. Why not declare it once (in ChallengesViewModel, for example), and pass that single instance to everyone else who needs it? Is that not possible?

1 Like

I had exactly the same doubts while reading and thought of at least 3 downsides of the original approach from the book:

  1. Everyone can write/set the value, even though only the SettingsView is supposed to have such permission.
  2. A redundant UserDefaults abstraction is leaked for read-only cases.
  3. Renaming the key or updating the default value is error-prone because it’s copy-pasted everywhere.

I’m new to SwiftUI/Combine but it looks like something like @Binding can be used everywhere else except for SettingsView.