Using envvault with Swift
Note: Please ensure that you have completed the previous steps
Prerequisites
- Swift installed
- envvault CLI tool installed
- An existing Swift project
Usage
Running Your Application
To run your Swift application with environment variables from envvault:
$ envvault run --env=dev swift run
Caching Environment Variables
For better performance, you can cache your environment variables:
$ envvault run --env=dev -c -- swift run
Example Implementation
Here is how to set up a basic Swift Vapor application with envvault:
// main.swift
import Vapor
// Your environment variables are automatically loaded
let port = Environment.get("PORT") ?? "8080"
let dbUrl = Environment.get("DB_URL") ?? ""
let app = try Application(.detect())
defer { app.shutdown() }
app.get { req async -> String in
return "Hello from envvault!"
}
try app.server.start(hostname: "127.0.0.1", port: Int(port) ?? 8080)
defer { app.server.shutdown() }
try app.run()
// Package.swift
// swift-tools-version:5.5
import PackageDescription
let package = Package(
name: "MyApp",
dependencies: [
.package(url: "https://github.com/vapor/vapor.git", from: "4.0.0"),
],
targets: [
.target(name: "App", dependencies: [.product(name: "Vapor", package: "vapor")])
]
)