On page 202, why does this not cause the ratings string stored in User Defaults to be overwritten with “0000” each time the app is launched?
@AppStorage(“ratings”) private var ratings = “0000”
If I run the app and set a rating of “4” for the first exercise, the value of the ratings key would be “4000”
Then if I kill the app and launch it again, when the line,
@AppStorage(“ratings”) private var ratings = “0000” is executed,
why isn’t the ratings string stored in User Defaults updated to “0000”?
@AppStorage
is a special property wrapper that reads the property value for the name provided from the UserDefaults preference file.
It’s just like initializing any other property. For example:
var someVar = "some value"
On initialization, someVar
is the assigned value, but you can change that.
On initialization of the AppStorage
property, the app will first read the UserDefaults preference file stored in Library/Preferences to see if ratings
already exists in the file. If it doesn’t, ratings
is assigned 0000
.
2 Likes