Environment Functions
Read, set, and manage environment variables with .env file support.
Environment Variables
getenv(name)
Get the value of an environment variable.
Parameters
name : String - The environment variable name
Returns
String? - The value or null if not set
let db_url = getenv("DATABASE_URL")
let port = getenv("PORT") ?? "3000"
setenv(name, value)
Set an environment variable.
Parameters
name : String - The variable namevalue : String - The value to setsetenv("MY_VAR", "my_value")
setenv("DEBUG", "true")
hasenv(name)
Check if an environment variable is set.
Returns
Bool - true if the variable exists
if hasenv("DEBUG") {
println("Debug mode enabled")
}
.env File Support
dotenv(path?)
Load environment variables from .env files.
Parameters
path : String? - Optional path to a specific .env file
Behavior
Without a path, loads
.env and .env.{APP_ENV} automatically.
// Load default .env files
dotenv()
// Load a specific file
dotenv(".env.production")
dotenv(".env.local")
Common Patterns
Configuration Management
// Load environment at startup
dotenv()
// Configuration with defaults
let config = {
"database_url": getenv("DATABASE_URL") ?? "postgres://localhost/dev",
"port": int(getenv("PORT") ?? "3000"),
"debug": getenv("DEBUG") == "true",
"secret_key": getenv("SECRET_KEY")
}
// Validate required config
if !config["secret_key"] {
panic("SECRET_KEY environment variable is required")
}