Environment Variables in Swift
Environment variables are a universal mechanism for conveying configuration information to Unix programs. Let’s look at how to set, get, and list environment variables.
Running the program shows that we pick up the value for FOO
that we set in the program, but that BAR
is empty.
The list of keys in the environment will depend on your particular machine.
If we set BAR
in the environment first, the running program picks that value up.
In Swift, we use the ProcessInfo.processInfo.environment
property to access environment variables. This property is a dictionary that contains all the environment variables. We can use the setenv()
function to set environment variables, and access them using the dictionary subscript syntax.
The ProcessInfo.processInfo.environment
property returns all environment variables as a dictionary, which we can iterate over to get all keys. This is equivalent to the os.Environ()
function in the original example.
Note that in Swift, we don’t need to split the environment variables ourselves, as they are already provided as key-value pairs in the dictionary.