Swiftpack.co - SwiftOnTheServer/SwiftDotEnv as Swift Package

Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
See all packages published by SwiftOnTheServer.
SwiftOnTheServer/SwiftDotEnv 2.0.1
Swift library that loads environment variables from .env files into the environment
⭐️ 65
🕓 2 years ago
.package(url: "https://github.com/SwiftOnTheServer/SwiftDotEnv.git", from: "2.0.1")


:warning: This repository is archived as I'm no longer using Swift on Linux and so maintaining isn't appropriate.

Swift 4 library that loads environment variables from .env into the environment inspired by the Ruby dotenv and PHP dotenv projects.


Storing configuration in the environment is one of the tenets of a twelve-factor app. Anything that is likely to change between deployment environments–such as resource handles for databases or credentials for external services–should be extracted from the code into environment variables.

But it is not always practical to set environment variables on development machines or continuous integration servers where multiple projects are run. SwiftDotEnv loads variables from a .env file into ENV when the environment is bootstrapped.


Install using Swift Package Manager.

Swift version

Version 2 of this module has been tested with Swift 4.0. Version 1 has been tested with Swift 3.0 and 3.1.


import DotEnv

let env = DotEnv(withFile: ".env")

let host = env.get("DB_HOST") ?? "localhost"
let port = env.getAsInt("DB_PORT") ?? 3306
let isEnabled = env.getAsBool("IS_ENABLED") ?? true

An example .env file would be:


There are three getter methods:

  • get() returns a String?
  • getAsInt() returns an Int?
  • getAsBool() returns a Bool? where case-insensitive "true", "yes" and "1" evaluate to true

You can also use subscript access to retrieve the string version:

let host = env["DB_HOST"] ?? "localhost"

As a convenience, you can use env.all() to retrieve all environment variables.

Note that the .env file is referenced relative to the directory where the binary is executed from.


Currently has a very naive parser of the .env file and so doesn't support multi-line values.


Contributions welcome! Please put your changes in a separate branch from master and raise a PR.


Stars: 65
Last commit: 2 years ago
jonrohan Something's broken? Yell at me @ptrpavlik. Praise and feedback (and money) is also welcome.

Related Packages

Release Notes

4 years ago

Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics