102

Does anybody know how I can grab an environment variable in Swift?

1

6 Answers 6

133

Swift 3 and up:

import Foundation

if let value = ProcessInfo.processInfo.environment["KEY"] {
    ...
}
3
  • 5
    Careful. These env vars won't show up when you archive or launch the app away from Xcode. Commented Oct 28, 2022 at 22:34
  • 1
    @joshuakcockrell I learned it the hard way. Your comment saved me from another sleepless night. Thank you.
    – ASCIImo
    Commented Nov 29, 2023 at 13:05
  • Use this if you want your env vars to persist even after archiving/shipping to TestFlight and/or App Store: stackoverflow.com/a/74254208/4975772 Commented Nov 29, 2023 at 19:55
40

Along with the NSProcessInfo-based method mentioned by Oleg, you can access environment variables using the the standard C getenv function, like so:

Swift 2.x:

func getEnvironmentVar(name: String) -> String? {
    let rawValue = getenv(name)
    guard rawValue != nil else { return nil }
    return String(UTF8String: rawValue)
}

Swift 3.0:

func getEnvironmentVar(_ name: String) -> String? {
    guard let rawValue = getenv(name) else { return nil }
    return String(utf8String: rawValue)
}

It's also possible to set environment variables using the setenv function:

func setEnvironmentVar(name: String, value: String, overwrite: Bool) {
    setenv(name, value, overwrite ? 1 : 0)
}

The reason I mention the ability to set variables is because it's the only way I know of to set variables when working in an Xcode Playground.

I recently wanted to see a backtrace for a strange CGContext error I was getting when working with a "live" view in a playground. By default, the backtrace isn't shown in the console, so I had to set the CG_CONTEXT_SHOW_BACKTRACE environment variable to see what was up:

setenv("CG_CONTEXT_SHOW_BACKTRACE", "1", 1)

After that, it was smooth sailing. Well, other than the CGContext error I was getting, but that's a topic for another day.

Hope this helps!

P.S. The above functions require the Darwin module to be imported. Foundation automatically imports Darwin, but I thought I should mention it nonetheless.

4
  • If you want to set environment variables for an Xcode project you can edit scheme > run > arguments section where you can add environment variables Commented Apr 4, 2019 at 3:38
  • thank you for the setenv tip. tried to make it work before with Process() and ProcessInfo.processInfo but couldn't never make the env stick. setenv fixes the issue for me.
    – godbout
    Commented Mar 16, 2021 at 17:43
  • didn't know about setenv--thanks!
    – spnkr
    Commented Apr 7, 2022 at 6:22
  • setenv(...) to help with tests - thank you!
    – Mark
    Commented Jul 9 at 18:43
16

Yes it is possible. Use ProcessInfo for that.

Simple example :

let dic = ProcessInfo.processInfo.environment
if dic["VAR"] != nil {

}
1
  • 2
    Ok, that work on running application, what do you do with the UI Tests?
    – Maetschl
    Commented Apr 8, 2017 at 13:21
13

Since Swift 3 NSProcessInfo has been renamed to ProcessInfo. And method processInfo() has been replaced with property processInfo.

import Foundation

for (key, value) in ProcessInfo.processInfo.environment {
    print("\(key): \(value)")
}
1
1

Alternatively you can use Info.plist file to store build-time env variables that your app needs at runtime, as described on apple developers forum:

For example if you have a MyConfig.xcconfig file like this:

MY_SECRET_API_KEY = mysupersecretapikeyvaluehere

In your Info.plist you should add an entry like this:

<key>MySecretApiKey</key>
<string>$(MY_SECRET_API_KEY)</string>

Finally in your code read the value of your variable like this:

guard let infoDictionary: [String: Any] = Bundle.main.infoDictionary else { return }
guard let mySecretApiKey: String = infoDictionary["MySecretApiKey"] as? String else { return }
print("Here's your api key value -> \(mySecretApiKey)")
1

A Vapor specific solution:

From the code which Vapor automatically generates as a project template:

let variable = Environment.get("VARIABLE") ?? "or-the-default"
2
  • That API is specific to Vapor. Commented Mar 7, 2022 at 3:37
  • This is correct, but doesn't answer the OP's question.
    – RobMac
    Commented Feb 27 at 10:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.