sindresorhus/Defaults

Support initial value for optional key

Open

#54 创建于 2020年10月24日

在 GitHub 查看
 (4 评论) (1 反应) (0 负责人)Swift (2,465 star) (162 fork)user submission
enhancementhelp wanted

描述

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:) returns nil whether it's unset or set to nil.
  • suite.dictionaryRepresentation().keys.contains(key) returns nil whether it's unset or set to nil.
  • 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...
  • CFPreferencesCopyValue returns the true value ignoring the suite.register defaults, but it requires a suite name.

Possible solutions:

  1. Force passing a suiteName parameter too if you want to use initialValue with a non-standard suite. (and use CFPreferencesCopyValue)
  2. Keep track of keys that are set in an internal UserDefaults entry.
  3. Other ideas?

贡献者指南