Structure
KeyMappingProvider
A configuration provider that maps all keys before delegating to an upstream provider.
- iOS 18.0+
- macOS 15.0+
- tvOS 18.0+
- visionOS 2.0+
- watchOS 11.0+
struct KeyMappingProvider<Upstream> where Upstream : ConfigProvider
Mentioned In
Overview
Use KeyMappingProvider to automatically apply a mapping function to every configuration key before passing it to an underlying provider. This is particularly useful when the upstream source of configuration keys differs from your own. Another example is namespacing configuration values from specific sources, such as prefixing environment variables with an application name while leaving other configuration sources unchanged.
Common use cases
Use KeyMappingProvider for:
Example
Use KeyMappingProvider when you want to map keys for specific providers in a multi-provider setup:
// Create providers
let envProvider = EnvironmentVariablesProvider()
let jsonProvider = try await FileProvider<JSONSnapshot>(filePath: "/etc/config.json")
// Only remap the environment variables, not the JSON config
let keyMappedEnvProvider = KeyMappingProvider(upstream: envProvider) { key in
key.prepending(["myapp", "prod"])
}
let config = ConfigReader(providers: [
keyMappedEnvProvider, // Reads from "MYAPP_PROD_*" environment variables
jsonProvider // Reads from JSON without prefix
])
// This reads from "MYAPP_PROD_DATABASE_HOST" env var or "database.host" in JSON
let host = config.string(forKey: "database.host", default: "localhost")
Convenience method
You can also use the prefixKeys(with:) convenience method on configuration provider types to wrap one in a KeyMappingProvider:
let envProvider = EnvironmentVariablesProvider()
let keyMappedEnvProvider = envProvider.prefixKeys(with: ["myapp", "prod"])
Topics
Creating a key-mapping provider
Relationships
Conforms To