Swift environment configuration loader with validation
Swift
import Foundation
struct AppConfig {
let host: String
let port: Int
let debug: Bool
static func load(
_ env: [String: String] = ProcessInfo.processInfo.environment
) throws -> AppConfig {
let portText = env["PORT"] ?? "8080"
guard let port = Int(portText), (1...65535).contains(port) else {
throw ConfigError.invalid("PORT must be 1-65535, got \(portText)")
}
let host = env["HOST"].flatMap { $0.isEmpty ? nil : $0 } ?? "127.0.0.1"
let debug = ["1", "true", "yes"].contains(env["DEBUG"]?.lowercased() ?? "")
return AppConfig(host: host, port: port, debug: debug)
}
}
enum ConfigError: Error { case invalid(String) }