Swift 5 library for accessing environment variables from .env files
Find a file
2021-05-05 22:30:58 +02:00
.github/workflows Create swift.yml 2021-05-05 22:30:58 +02:00
.swiftpm/xcode initial 2021-05-03 14:14:19 +02:00
Sources/SwiftDotEnv Added Readme 2021-05-03 14:45:13 +02:00
Tests/SwiftDotEnvTests initial 2021-05-03 14:14:19 +02:00
.gitignore Added Readme 2021-05-03 14:45:13 +02:00
Package.swift Initial Commit 2021-05-03 12:31:56 +02:00
README.md Added Readme 2021-05-03 14:45:13 +02:00

SwiftDotEnv

Swift 5 library for accessing environment variables from .env files

Installation

Install using Swift Package Manager.

Add Dependency:

.package(name: "SwiftDotEnv", url: "https://github.com/noahkamara/swiftdotenv", from: "1.0.0")

Usage

import SwiftDotEnv

let envPath = ".env" // or absolute path
let env = DotEnv(withFile: envPath)

// Retrieve variable 'VAR' and default to "DEFAULTVALUE"
let var = env.value("VAR", "DEFAULTVALUE")

Getter Methods:

value(_ key: String, _ default: String? = nil) -> String? 

Returns the value forkey in the environment, returning default if not present

  • Parameter key: Variable key
  • Parameter default: Default value
int(for key: String, _ default: Int? = nil) -> Int?

Returns the integer value for key in the environment, returning default if not present

  • Parameter key: Variable key
  • Parameter default: Default value
bool(for key: String, _ default: Bool? = nil) -> Bool?

Returns the boolean value for key in the environment, returning default if not present

  • Parameter key: Variable key
  • Parameter default: Default value

Subscript Access:

You can also access variables by subscript (this will return a string!)

let var = env["VAR"]

The .env-file

This is an example for a .env file and also all supported types:

# COMMENT
STRING=ThisIsAString # Inline Comment
STRING_QUOTMARK="String with"
INT=69
BOOL_TRUE=true
BOOL_TRUE_INT=1
BOOL_TRUE_STR=yes
BOOL_FALSE=false
BOOL_FALSE_INT=0
BOOL_FALSE_STR=no

Support for Values-Types

Comments

# This is a comment
KEY=VALUE

Inline Comments

KEY=VALUE # Inline Comment

Strings

STRING=ThisIsASupportedString
QUOTES="This is also a supported String"

Integers

INTEGER=42

Booleans

# Will be evaluated as true:
BOOL1=true
BOOL2=1
BOOL3=yes

# Will be evaluated as false
BOOL4=false
BOOL5=0
BOOL6=no