sindresorhus / Defaults

💾 Swifty and modern UserDefaults
https://swiftpackageindex.com/sindresorhus/Defaults/documentation/defaults
MIT License
1.93k stars 115 forks source link

Default value is not stored, which means the read value can change unexpectedly. #153

Closed ConfusedVorlon closed 7 months ago

ConfusedVorlon commented 7 months ago

Imagine the following. Server has a random id - which can be reset if needed.

extension Defaults.Keys {
   static let vidServerId = Key<String>("vidServerId",default:UUID().uuidString)
}

Expected

1) on first read, I get a random value 2) when I relaunch the app - I get the same value

Actual

every time I launch the app - I get a new value.


It seems that the default is read each time on launch and saved into the default values. This means that when you read a default value - you can't tell whether it is a saved value, or one that might change.

The same issue could cause wierd behaviour with user preferences

extension Defaults.Keys {
   static let importantChoice = Key<Bool>("choice",default:false)
}

After install: User A left the choice unchanged User B changed to true, then back to false

If I update my app to change the default

extension Defaults.Keys {
   static let importantChoice = Key<Bool>("choice",default:true)
}

Now - I have changed the setting for User A, but not for User B.

sindresorhus commented 7 months ago

This is just how native NSUserDefaults works, and is in my opinion, the expected behavior. It's a default fallback value, not an initial value. Even if I agreed with you, it would be too late to change the behavior of this now.

To achieve what you want, you can do Defaults[.vidServerId] = Defaults[.vidServerId] at launch.