Close Menu
geekfence.comgeekfence.com
    What's Hot

    refurbed and GoPro announce exclusive partnership in Ireland

    March 28, 2026

    Enterprise Network Trends & Strategy: WAN Manager Survey Insights

    March 28, 2026

    Posit AI Blog: De-noising Diffusion with torch

    March 28, 2026
    Facebook X (Twitter) Instagram
    • About Us
    • Contact Us
    Facebook Instagram
    geekfence.comgeekfence.com
    • Home
    • UK Tech News
    • AI
    • Big Data
    • Cyber Security
      • Cloud Computing
      • iOS Development
    • IoT
    • Mobile
    • Software
      • Software Development
      • Software Engineering
    • Technology
      • Green Technology
      • Nanotechnology
    • Telecom
    geekfence.comgeekfence.com
    Home»iOS Development»Swift and .env | Cocoanetics
    iOS Development

    Swift and .env | Cocoanetics

    AdminBy AdminDecember 7, 2025No Comments4 Mins Read0 Views
    Facebook Twitter Pinterest LinkedIn Telegram Tumblr Email
    Swift and .env | Cocoanetics
    Share
    Facebook Twitter LinkedIn Pinterest Email


    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: " 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.

    Like this:

    Like Loading…

    Related


    Categories: Administrative



    Source link

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email

    Related Posts

    ios – What is the correct way to initialize a Data property in a model object in SwiftData / CloudKit?

    March 28, 2026

    Ultimate UICollectionView guide with iOS examples written in Swift

    March 24, 2026

    app store – Guideline 3.1.1 – Business – Payments – In-App Purchase in ios reject

    March 23, 2026

    More Updates from the Swift Workshop

    March 19, 2026

    How to use iCloud drive documents?

    March 18, 2026

    ios – Video input to Shortcuts action

    March 17, 2026
    Top Posts

    Understanding U-Net Architecture in Deep Learning

    November 25, 202527 Views

    Hard-braking events as indicators of road segment crash risk

    January 14, 202624 Views

    Redefining AI efficiency with extreme compression

    March 25, 202619 Views
    Don't Miss

    refurbed and GoPro announce exclusive partnership in Ireland

    March 28, 2026

    refurbed, Ireland’s leading online marketplace for refurbished goods, has launched an exclusive new partnership with…

    Enterprise Network Trends & Strategy: WAN Manager Survey Insights

    March 28, 2026

    Posit AI Blog: De-noising Diffusion with torch

    March 28, 2026

    The Path to Agentic-Ready Data: Takeaways from the Gartner Data & Analytics Summit

    March 28, 2026
    Stay In Touch
    • Facebook
    • Instagram
    About Us

    At GeekFence, we are a team of tech-enthusiasts, industry watchers and content creators who believe that technology isn’t just about gadgets—it’s about how innovation transforms our lives, work and society. We’ve come together to build a place where readers, thinkers and industry insiders can converge to explore what’s next in tech.

    Our Picks

    refurbed and GoPro announce exclusive partnership in Ireland

    March 28, 2026

    Enterprise Network Trends & Strategy: WAN Manager Survey Insights

    March 28, 2026

    Subscribe to Updates

    Please enable JavaScript in your browser to complete this form.
    Loading
    • About Us
    • Contact Us
    • Disclaimer
    • Privacy Policy
    • Terms and Conditions
    © 2026 Geekfence.All Rigt Reserved.

    Type above and press Enter to search. Press Esc to cancel.