Defaults icon indicating copy to clipboard operation
Defaults copied to clipboard

Derived keys

Open sindresorhus opened this issue 3 years ago • 0 comments

I have encountered a need where I would like to create a new key where the value is derived from one or more existing keys.

For example, let's say you have a .name and .email key. You might want to simplify the checking and have a .hasFilledOutAllFields key. This key would be derived from the former keys.

The reason it has to be in Defaults and not just in a custom extension is that it needs to be reactive. So that, if either .name or .email changes, .hasFilledOutAllFields triggers an update too.

My initial thoughts are something like this:

extension Defaults.Keys {
	static let hasFilledOutAllFields = Key<Bool>(derivedFrom: .name, .email) { name, email in
		!name.isEmpty && !email.isEmpty
	}
}

Another use-case is needing the derived key to be settable too. Not sure how that would look like though.

And maybe it would be useful to be able to listen to external events too. For example, for the .hasFilledOutAllFields key, we might also need to ensure the keyboard is not shown or something.

Maybe there's a more general way we could handle this. I'm open to ideas.

sindresorhus avatar Apr 19 '21 08:04 sindresorhus