Use environment variables from .env file in a Swift Package

I am a Software Engineer working on open source and enterprise mobile SDKs for iOS and MacOS developers written in Swift. From 🇩🇪 and happily living in 🇺🇸
Search for a command to run...

I am a Software Engineer working on open source and enterprise mobile SDKs for iOS and MacOS developers written in Swift. From 🇩🇪 and happily living in 🇺🇸
No comments yet. Be the first to comment.
WWDC26 kicked off on June 8, 2026. The information in this article reflects the information published by Apple on that date. There are 14 new frameworks. Name Description AccessoryAccess Manage

WWDC25 kicked off on June 9, 2025. The information in this article reflects the information published by Apple on that date. New Frameworks NameDescription AlarmKitSchedule prominent alarms and countdowns to help people manage their time. AVR...

WWDC25 is almost here, and I couldn’t be more excited! Whether you're attending the official events, community meetups, or just soaking in the energy around Cupertino, there’s no better time to connect, share ideas, and celebrate everything we love a...

In this blog post, I’ll share an observation and advice regarding the caching behavior of network responses by Apple’s APIs. If you are unfamiliar with caching of network responses then I recommend Apple’s article Accessing cached data that introduce...
WWDC24 kicked off on June 10, 2024. The information in this article reflects the information published by Apple on that date. New Frameworks NameDescription AccessorySetupKitUse AccessorySetupKit to discover accessories with Bluetooth or Wi-Fi...

You can use Environment variables to pass secret information to a process at runtime instead of hardcoding that information during build time.
Multiple environment variables can be stored in a .env file but should not be committed to your repository.
In my example I want to pass MY_API_KEY variable with value 12345 to my Swift Package.
I will use ProcessInfo.processInfo.environment to access the value in my Swift Package .
public var myApiKey: String? {
ProcessInfo.processInfo.environment["MY_API_KEY"]
}
But how to pass the environment value in the first place?
A test case with the following assertion ...
XCTAssertEqual(MySecrets().myApiKey, "12345")
... will fail because of the missing environment variable.
Once I set the individual environment variable and then run the tests ...
export MY_API_KEY='12345'
swift test
... the test will pass successfully.
.env fileI created the following .env file on my local machine.
MY_API_KEY=12345
I can pass all environment variables with the following utility script setenv.sh
#!/usr/bin/env bash
# Credit: https://zwbetz.com/set-environment-variables-in-your-bash-shell-from-a-env-file/
# Show env vars
grep -v '^#' .env
# Export env vars
export $(grep -v '^#' .env | xargs)
Only two commands are needed to pass all environment variables and run the tests.
source setenv.sh
swift test