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.

import Foundation

// To set a key/value pair, use setenv(). To get a
// value for a key, use getenv(). This will return
// nil if the key isn't present in the environment.

setenv("FOO", "1", 1)
print("FOO:", ProcessInfo.processInfo.environment["FOO"] ?? "")
print("BAR:", ProcessInfo.processInfo.environment["BAR"] ?? "")

// Use ProcessInfo.processInfo.environment to get all key/value pairs in the
// environment. This returns a dictionary of strings.
// Here we print all the keys.

print()
for (key, _) in ProcessInfo.processInfo.environment {
    print(key)
}

Running the program shows that we pick up the value for FOO that we set in the program, but that BAR is empty.

$ swift run
FOO: 1
BAR: 

TERM_PROGRAM
PATH
SHELL
...
FOO

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.

$ BAR=2 swift run
FOO: 1
BAR: 2
...

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.