UserDefaults.register(defaults:) Is a Bit Like Nil-Coalescing
I suggested the use of UserDefaults.register(defaults:)
today. During the conversation, I realized that this behaves very much like the Optional
/Nil-Coalescing operator ??
.
- When
UserDefaults
have a stored value for a key, it’s like.some(...)
. - When
UserDefaults
don’t have a stored value for a key, theregister(defaults:)
collection is used as a fallback. - When
UserDefaults
don’t have a stored value for a key and there’s no registered default value, you get the system default for the given type – e.g.false
for a boolean, or0
for a number.
So for this call:
let value: Bool = UserDefaults.standard.bool(forKey: "i_can_has_cheezburger")
I imagine something like this happens:
boolFromApplicableDomains(forKey: "i_can_has_cheezburger")
?? registeredDefaults["i_can_has_cheezburger"] as? Bool
?? Bool.defaultValue // => false