What to do when the value is nil?
I decided to use two UserDefaults fields: (isNil: Bool, date: Date)
Despite my usage, since 2013, of UserDefaults
and its predecessor, I did not realize until a few minutes ago that UserDefaults
can store Date
s directly. I have historically converted Date
s to ISO 8601 String
s using DateFormatter
and stored the String
s. If you take this approach, you could store something like none
for missing Date
s. When you load that and attempt to create a Date
, the fact that the creation fails will indicate the missing Date
.
Do you need to distinguish a nil value from "not in the defaults at all"? If not, you can store the Date?
directly; setting nil
will delete the key from the store.
I think this should work for me. I'm trying to implement "undo": to allow "peak" at some new Date to see what will happen. When the user is done looking, they can "go back" to the old Date. So deleting the key to represent nil should work for me.
Thanks!