Swift Configuration Library - swiftbox-config

Hello,

I would like to share with you a library that we've opensourced some time ago.
Here is repository: GitHub - allegro/swiftbox-config

Share with us what you think :slight_smile:

Quick overview below:

Swiftbox-config

Swiftbox-config is type-safe configuration library for Swift projects.
SwiftBox Configuration allows to pass type-safe configuration such as command line, environment variables and external providers (e.g Vault) by declaring one simple struct. Configuration can be inherited from multiple sources simultaneously.

Feed the configuration with:

  • Command line arguments: ./yourapp --config:simple=test --config:nested.number=1 --config:array.0=string
  • Environment variables: SIMPLE=test NESTED_NUMBER=1 ARRAY_0=string ./yourapp
  • JSON
  • Dictionary
  • Custom sources

SwiftBox Configuration supports:

  • overriding (source that is declared later can override previous values)
  • inheritance
  • optionals
  • type-safety
  • nesting (structs and arrays)
  • environment variables prefixes (avoid conflicting with system variables)

How to use

  1. Declare your configuration as a struct
struct Conf: Configuration {
    let simple: String
    let int: Int
    let double: Double
    let nested: NestedConf // nested configuration
    let array: [String?] // array of optionals
    let arraynested: [NestedConf] // nested array

    struct NestedConf: Configuration {
        let value: String? // optional
    }
}
  1. Add extension ConfigManager class.
extension Conf: ConfigManager {
    public static var configuration: Conf? = nil
}
  1. Bootstrap your configuration from declared sources
try Conf.bootstrap(from: [
    DictionarySource(dataSource: ["test": 1]),
    EnvSource(),
    JSONSource(dataSource: "{\"test\": \"sample\"}"),
    CommandLineSource(prefix: "--config:my-prefix-")
])
  1. Use it in your app
Conf.global.simple
Conf.global.int
Conf.global.double
Conf.global.array[0] // Optional[String]
Conf.global.nested.value // Optional[String]
Conf.global.arraynested[0].value // Optional[String]
2 Likes