EnvironmentVariable

@propertyWrapper
public struct EnvironmentVariable<T>

A property wrapper that uses the specified environment variable name for property access and backing storage.

The following example shows how to use the EnvironmentVariable property wrapper to expose static properties backed by enviornment variables ("HOST" and "PORT").

enum ServerSettings {
    @EnvironmentVariable(name: "HOST")
    static var host: URL?

    @EnvironmentVariable(name: "PORT", defaultValue: 8000)
    static var port: Int
}
  • The environment variable value converted to type T using the EnvironmentStringConvertible protocol for the specified environment variable name if name is in the environment; otherwise, the specified defaultValue.

    Declaration

    Swift

    public var wrappedValue: T { get nonmutating set }
  • Instantiates an EnvironmentVariable property wrapper for the specified environment variable name and default value.

    Declaration

    Swift

    public init(name: String, defaultValue: T)

    Parameters

    name

    The environment variable name to use for property access and backing storage.

    defaultValue

    The default value to use if the name does not exist in the environment or if type conversion fails.

  • Instantiates an EnvironmentVariable property wrapper for the specified environment variable name and default value.

    Declaration

    Swift

    public init<U>(name: String, defaultValue: T = nil) where T == U?, U : EnvironmentStringConvertible

    Parameters

    name

    The environment variable name to use for property access and backing storage.

    defaultValue

    The default value to use if the name does not exist in the environment or if type conversion fails.