Ad

Our DNA is written in Swift
Jump

Swift and .env

I’ve started doing occasional live streams, and when presenting to a worldwide audience, you don’t want your secrets visible on YouTube. For example, if you have an OPENAI API key, anyone could use your credits if they get hold of it. Plus, hard-coding secrets into a git repo is never good practice because once they’re committed, they’re difficult to remove entirely.

The standard solution, especially in server-side development, is to use a .env file to store secrets. The leading period makes the file hidden by default. Typically, your .gitignore file will exclude .env files. So, after checking out a project, the first step is to set up your .env file by copying .env.example and replacing the placeholders with actual values.

# IMAP Server Credentials
IMAP_HOST=mail.example.com
IMAP_PORT=993
IMAP_USERNAME=oliver@drobnik.com
IMAP_PASSWORD=secret

This format is straightforward and widely used across different programming languages. It keeps sensitive information out of your source code while still being easy to access during development.

Using .env Files in Python

In Python, you might use this approach with the dotenv package:

from dotenv import load_dotenv
import os

# Load environment variables from the .env file
load_dotenv()

# Access the variables
database_url = os.getenv("DATABASE_URL")
secret_key = os.getenv("SECRET_KEY")
debug_mode = os.getenv("DEBUG")

print(database_url, secret_key, debug_mode)

This makes it easy to manage configuration settings without hardcoding them into your code.

Using .env Files in Swift

To achieve the same in Swift, we use the SwiftDotenv package by Brendan Conron. This package is straightforward and works similarly to dotenv in other languages.

Step 1: Add SwiftDotenv to Package.swift

.package(url: "https://github.com/thebarndog/swift-dotenv", from: "2.1.0")

Step 2: Import and Configure the Package

By default, SwiftDotenv loads the .env file from the current working directory (CWD). If you run your app from Xcode, the CWD is usually the project root directory. However, when using swift run, the CWD may be different, depending on your terminal setup. Ensure you’re in the correct directory before executing your app.

import SwiftDotenv

try Dotenv.configure()

If needed, you can specify a different path:

try Dotenv.configure(atPath: ".env.development")

Step 3: Access Environment Variables

You can access environment variables in two ways: using subscripts or dynamic member lookup.

Using Subscripts

if let server = Dotenv["IMAP_SERVER"]?.stringValue {
    print("IMAP_SERVER: \(server)")
} else {
    print("IMAP_SERVER: Not found")
}

Using Dynamic Member Lookup

if case let .string(host) = Dotenv.imapHost {
    print("IMAP_HOST: \(host)")
} else {
    print("IMAP_HOST: Not found")
}

Dynamic member lookup is a Swift feature where property names like imapHost are automatically mapped to corresponding .env keys. This makes the code cleaner and easier to read.

Enum Representation of Values

SwiftDotenv stores all values as strings, but the Dotenv.Value enum represents possible data types:

enum Dotenv.Value {
    case boolean(Bool)
    case double(Double)
    case integer(Int)
    case string(String)
}

This flexibility allows you to cast values to the appropriate types as needed.

The Trouble with the Working Directory

When you run the terminal app you created, the current working directory (CWD) is the same as the project root. Because of this, SwiftDotEnv can find the file without you specifying a path.

Besides running the terminal app via swift run, you can also open the Package.swift file in Xcode, which is particularly useful if you want to debug specific parts of your code. When you open a package like this, Xcode generates an Xcode project on the fly. However, the build directory is located somewhere in DerivedData, which means the terminal app won’t find the .env file.

I tried to come up with a smart way to auto-detect the location of the .env file, but it didn’t work out. I experimented with various environment variables suggested by ChatGPT, but none of them worked. In the end, I simply specified the project folder directly as the custom working directory.

This approach works fine because the Xcode project file (.xcodeproj) doesn’t get checked into the repo. You can mention this step in the README file, noting that you only need to do it once. After that, you can easily switch between running your code via swift run or building and running it from Xcode.

Conclusion

Using .env files with SwiftDotenv allows you to securely store sensitive information without hardcoding it into your source code. It’s a simple and effective way to keep your API keys, credentials, and other secrets safe.

This approach aligns with best practices used in other programming languages, making your code more maintainable and secure. It ensures that sensitive information is protected while still being easily accessible during development.

I’ve uploaded a working sample on GitHub if you want to see the complete setup. Additionally, you can watch my YouTube live stream where I demonstrate this process: Watch the live stream.


Categories: Administrative

1 Comment »

Trackbacks

  1. 快速和 .env - 偏执的码农

Leave a Comment