sindresorhus / sindresorhus/Defaults
Support initial value for optional key
Nobody has claimed this yet.
- Dominant language
- Swift
- Stars
- 2.5k
- Forks
- 163
- PR merge metrics
- No merged PRs in 30d
Description
I have:
extension Defaults.Keys {
static let refreshInterval = Key<TimeInterval?>("refreshInterval")
}
And I would like to specify an initial value, meaning one that is used before any value is set. This is different from default, which is used whenever the value is nil, which would not work here as it would make it impossible to set the value to nil, which is the whole point of making the value optional.
What I'm thinking:
extension Defaults.Keys {
static let refreshInterval = Key<TimeInterval?>("refreshInterval", initialValue: 3600)
}
The problem is that there's no good way to differentiate whether a key unset or nil.
object(forKey:)returnsnilwhether it's unset or set tonil.suite.dictionaryRepresentation().keys.contains(key)returnsnilwhether it's unset or set tonil.suite.persistentDomain(forName:).keys.contains(key)would work, but we only have the suite instance, not the suite name. And the suite instance doesn't expose the suite name...CFPreferencesCopyValuereturns the true value ignoring thesuite.registerdefaults, but it requires a suite name.
Possible solutions:
- Force passing a
suiteNameparameter too if you want to useinitialValuewith a non-standard suite. (and useCFPreferencesCopyValue) - Keep track of keys that are set in an internal UserDefaults entry.
- Other ideas?
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by tracing the Defaults.Keys Key initializer and how it handles UserDefaults suites. Compare object(forKey:), dictionaryRepresentation(), persistentDomain(forName:), and CFPreferencesCopyValue to determine how unset and explicitly nil values can be distinguished. Done means optional keys support an initialValue without preventing an explicit nil.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- swift
- Domain
- databases
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 30/100