Skip to Content
Course content

174: ProcessInfo for Environment Access

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I’ve seen a lot of developers start their projects by creating a Configuration.swift file. In it, they’ll define a bunch of constants like let apiBaseUrl = "https://dev-api.example.com". When it's time to ship to production, they manually change that string to the production URL, commit it, and push. It seems simple enough at first, but it's a recipe for disaster. I can't tell you how many times I've seen a "production" build accidentally ship with a staging database URL because someone forgot to flip a boolean flag or change a string before the merge.

The Hardcoded Headache

// The naive way: Manual toggles
struct Config {
    static let isProduction = false // Remember to change this!
    static let apiKey = "dev_key_12345"
    static let baseUrl = isProduction ? "https://api.myapp.com" : "https://dev.api.myapp.com"
}

The problem here isn't just the risk of human error; it's the security implication. If you're putting API keys directly in your Swift files, they're living in your version control. Even in a private repo, that's a bad habit. Plus, your code is now tightly coupled to your environment. To change a configuration value, you have to recompile the entire app. That's a slow loop when you're just trying to test a different backend endpoint.

Letting the OS Handle the Config

A much cleaner approach is to treat your configuration as external data that the application consumes at runtime. This is where ProcessInfo comes in. Specifically, ProcessInfo.processInfo.environment gives you access to a dictionary of the environment variables passed to the process by the operating system.

Instead of hardcoding a URL, you ask the system for it. In Xcode, you can set these variables in your Scheme (Product > Scheme > Edit Scheme > Run > Arguments > Environment Variables). This keeps the configuration separate from the logic.

// The better way: Dynamic environment access
extension ProcessInfo {
    var apiBaseUrl: String {
        // We look for the key, and provide a sensible fallback for local dev
        return processInfo.environment["API_BASE_URL"] ?? "https://dev.api.example.com"
    }
    
    var apiKey: String? {
        return processInfo.environment["API_KEY"]
    }
}

// Usage
let currentUrl = ProcessInfo.processInfo.apiBaseUrl
print("Connecting to \(currentUrl)...")

The Trade-off: Flexibility vs. Type Safety

Now, I'll be honest with you: you're trading some type safety here. ProcessInfo.processInfo.environment returns a [String: String]. You lose the compiler's ability to tell you that a variable is missing at build time. You're now relying on strings, and if you typo "API_BASE_URL" as "API_URL", you'll just get your fallback value (or nil) without a warning.

However, the trade-off is almost always worth it. You can now have different Schemes for "Staging", "QA", and "Production" that all use the exact same binary but behave differently based on the environment variables. You can also keep sensitive keys out of your source code entirely by managing them through your CI/CD pipeline's environment secrets. It moves the "source of truth" for configuration out of the code and into the environment where it belongs.




📋 Practical Task

Build an Environment-Aware API Client

Create a small Swift script or app component that simulates an API client. Your task is to implement the following:

  • Define an extension on ProcessInfo that retrieves two environment variables: APP_MODE (e.g., "Development" or "Production") and TIMEOUT_INTERVAL (a string representing seconds).
  • Implement a NetworkClient class that uses these values. If APP_MODE is "Development", the client should print a "DEBUG: Request sent" message before every simulated call.
  • The TIMEOUT_INTERVAL must be converted from a String to an Int. If the environment variable is missing or not a valid integer, it should default to 30.
  • Test your implementation by adding these variables to your Xcode Scheme and verifying that changing the values in the Scheme changes the program's output without you having to edit the code.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.