sunshinejr / SwiftyUserDefaults

Modern Swift API for NSUserDefaults
http://radex.io/swift/nsuserdefaults/static
MIT License
4.85k stars 366 forks source link

defaultValue is used when UserDefaults.get returns nil even for optionals #192

Open DivineDominion opened 5 years ago

DivineDominion commented 5 years ago

When the UserDefaults return nil, SwiftyUserDefaults falls back to using the defaultValue by default.

But what if you set e.g. a String? that can be nil?

I thought defaultValue would mean "the initial value", but apparently it doesn't. I think the current behavior is weird, though. Because you can sensibly use it to call register(defaults:) and have your initial fallback values be used on one hand, but then cannot get rid of it all all on the other.

I'd prefer to change the implementation to fall back to defaultValue for non-optional types, only.

sunshinejr commented 5 years ago

Hey @DivineDominion. Yeah, the default parameter name is a bit tricky with optional keys. Current implementation is basically "if there is a value, use it, if there is a nil, use the default value". I was debating if we should even have this initializer for optional keys but I decided to let is stay.

Falling back only for non-optional types would be inconsistent across implementations, though. I also don't want to save anything for user without a verbose call (e.g. DefaultsKey.save). Not sure what to do with that right now.