DEV Community

Wesley de Groot
Wesley de Groot

Posted on • Originally published at wesleydegroot.nl on

Snippet: @EnvironmentVariable

If you are creating commandline apps you sometimes need to acces the operating system environment variables, while you can use getenv(name) it can come in handy to use a property wrapper if you need to access the environment variables often, or if you are updating them.

Full code:

/// A property wrapper to set and get system's environment variables values. /// ///

 ``` /// @EnvironmentVariable(name: "PATH") /// var path: String? /// ```

 @propertyWrapper public struct EnvironmentVariable { var name: String public var wrappedValue: String? { get { guard let pointer = getenv(name) else { return nil } return String(cString: pointer) } set { guard let value = newValue else { unsetenv(name) return } setenv(name, value, 1) } } }

in the future i'll post more about @propertyWrappers.

Top comments (0)