🌳 Environment – a nicer, type-safe way of working with environment variables in Swift.

Overview

🌳 Environment

swift platforms version twitter
build jazzy codecov

Welcome to Environment – a nicer, type-safe way of working with environment variables in Swift.

Usage

Access Environment Variables

The Environment struct provides a type-safe API to get and set environment variables.

import Environment

let environment = Environment.environment

// Get "HOST" as String value
let host = environment["HOST"]

// Set "PORT" to String value of "8000"
environment["PORT"] = "8000"

Environment variables are accessed as String values by default, but can be converted to any type that conforms to EnvironmentStringConvertible.

// Get "HOST" as URL value
let host: URL? = environment["HOST"]

// Get "PORT" as Int value
let port: Int? = environment["PORT"]

// Set "PORT" to Int value of 8000
environment["PORT"] = 8000

// Get "APP_ID" as UUID value or use a default UUID if "APP_ID" is not set
let appID = environment["APP_ID"] ?? UUID()

Dynamic Member Lookup

The Environment struct also supports accessing environment variables using @dynamicMemberLookup.

// Get "HOST" as URL value using dynamic member lookup
let host: URL? = environment.HOST

// Set "PORT" to Int value of 8000 using dynamic member lookup
environment.PORT = 8000

Static Subscripts

The Environment struct supports static subscript access to environment variables in Swift 5.1.

import Environment
import Foundation

// Get "HOST" as URL value using static subscript
let host: URL? = Environment["HOST"]

// Set "PORT" to Int value of 8000 using static subscript
Environment["PORT"] = 8000

@dynamicMemberLookup also works with static subscripts.

// Get "HOST" as URL value using static dynamic member lookup
let host: URL? = Environment.HOST

// Set "PORT" to Int value of 8000 using static dynamic member lookup
Environment.PORT = 8000

Property Wrappers

The EnvironmentVariable property wrapper enables properties to be backed by environment variables in Swift 5.1.

The following example shows how to use the EnvironmentVariable property wrapper to expose static properties backed by enviornment variables ("HOST" and "PORT").

enum ServerSettings {
    @EnvironmentVariable(name: "HOST")
    static var host: URL?
    
    @EnvironmentVariable(name: "PORT", defaultValue: 8000)
    static var port: Int
}

Type-Safe Variables

Environment variables can be converted from a String representation to any type that conforms to the EnvironmentStringConvertible protocol.

Standard Library and Foundation types like Int, Float, Double, Bool, URL, UUID, Data, and more are already extended to conform to EnvironmentStringConvertible. Collection types like Array, Set, and Dictionary are also extended with conditional conformance.

You can add conformance to other classes, structures, or enumerations to enable additional types to be used as environment variables.

Custom EnvironmentStringConvertible Conformance

enum Beverage {
    case coffee
    case tea
}

extension Beverage: EnvironmentStringConvertible {
    init?(environmentString: String) {
        switch environmentString {
        case "coffee":
            self = .coffee
        case "tea":
            self = .tea
        default:
            return nil
        }
    }
    
    var environmentString: String {
        switch self {
        case .coffee:
            return "coffee"
        case .tea:
            return "tea"
        }
    }
}

let beverage: Beverage? = environment["DEFAULT_BEVERAGE"]

Default EnvironmentStringConvertible Conformance

A default implementation of EnvironmentStringConvertible is provided for types that already conform to LosslessStringConvertible or RawRepresentable.

For example, String-backed enums are RawRepresentable and may use the default implementation for EnvironmentStringConvertible conformance.

enum CompassPoint: String {
    case north
    case south
    case east
    case west
}

extension CompassPoint: EnvironmentStringConvertible { }

let defaultDirection: CompassPoint? = environment["DEFAULT_DIRECTION"]

API Documentation

Visit the online API reference for full documentation of the public API.

Installation

Environment requires Xcode 10 or a Swift 5 toolchain with the Swift Package Manager.

Swift Package Manager

Add the Environment package as a dependency to your Package.swift file.

.package(url: "https://github.com/wlisac/environment.git", from: "0.11.1")

Add Environment to your target's dependencies.

.target(name: "Example", dependencies: ["Environment"])
You might also like...
MQTagged provides a Tagged structure which helps differentiating between values of the same type.

MQTagged provides a Tagged structure which helps differentiating between values of the same type.

A Simple way help you drop or drag your source (like UIImage) between different App.

A Simple way help you drop or drag your source (like UIImage) between different App.

MicrofrontendGenerator - Script for creating micro frontends for Mobile in a simple and easy way

Introdução Template para a criação de SDK iOS. Existem duas opções de template:

ZakatFatoora - A simple way to implement e-invoicing (FATOORA) for iOS
ZakatFatoora - A simple way to implement e-invoicing (FATOORA) for iOS

ZakatFatoora - A simple way to implement e-invoicing (FATOORA) for iOS

A custom calculator for deg to rad conversion & the other way round
A custom calculator for deg to rad conversion & the other way round

Lilium Features A custom calculator for deg to rad conversion & the other way round. How to use Slide up the dock and you should see Lilium. An activa

Appwrite playground - a simple way to explore the Appwrite API & Appwrite Apple SDK

Appwrite's Apple Playground 🎮 Appwrite playground is a simple way to explore the Appwrite API & Appwrite Apple SDK. Use the source code of this repos

A novel way to set attributes to the Font in SwiftUI.

A novel way to set attributes to the Font in SwiftUI.

A powerful, beautiful way to experience Formula1

F1 Pocket Companion A powerful, beautiful way to experience Formula1, right on your iPhone Note This project will probably change it's name. I'm curre

A Swift package for encoding and decoding Swift Symbol Graph files.
A Swift package for encoding and decoding Swift Symbol Graph files.

SymbolKit The specification and reference model for the Symbol Graph File Format. A Symbol Graph models a module, also known in various programming la

Comments
  • Update Travis Linux build to use swiftenv install script from GitHub

    Update Travis Linux build to use swiftenv install script from GitHub

    https://swiftenv.fuller.li/install.sh went down and broke the Linux builds on Travis.

    This updates Travis to use the swiftenv install script directly from GitHub.

    opened by wlisac 0
  • Add @EnvironmentVariable property wrapper

    Add @EnvironmentVariable property wrapper

    Overview

    This adds support for an EnvironmentVariable property wrapper. This enables properties to be backed by environment variables in Swift 5.1.

    Usage

    The following example shows how to use the EnvironmentVariable property wrapper to expose static properties backed by enviornment variables ("HOST" and "PORT").

    enum ServerSettings {
        @EnvironmentVariable(name: "HOST")
        static var host: URL?
        
        @EnvironmentVariable(name: "PORT", defaultValue: 8000)
        static var port: Int
    }
    
    opened by wlisac 0
Releases(0.11.1)
Owner
Will Lisac
Swift and iOS
Will Lisac
Condense string literals into global variables.

Gettysburg This is an implementation of the SAX interface. API Documentation Documentation of the API can be found here: Gettysburg API A note on Char

Galen Rhodes 0 Nov 12, 2021
Fridax enables you to read variables and intercept/hook functions in Xamarin/Mono JIT and AOT compiled iOS/Android applications.

Fridax is a Node package for dealing with Xamarin applications while using the Frida API. Goal • Installation • Usage • Examples • Issues • License Bu

Northwave 125 Jan 3, 2023
UIEnvironment - A framework that mimics the SwiftUI view's environment to replicate the value distribution thought your UIKit app.

A framework that mimics the SwiftUI view's environment to replicate the value distribution thought your UIKit view hierarchy. Overview D

Łukasz Śliwiński 15 Dec 5, 2022
Wasmic allows you to run WebAssembly in a safe way on iOS.

wasmic-ios Bootstrap $ git clone https://github.com/kateinoigakukun/wasmic-ios.git $ git -c submodule."fastlane".update=none submodule update --init -

Yuta Saito 58 Dec 12, 2022
Turn your Swift data model into a working CRUD app.

Model2App is a simple library that lets you quickly generate a CRUD iOS app based on just a data model defined in Swift. (CRUD - Create Read Update De

Q Mobile 132 Dec 22, 2022
A thread safe throttle written in Swift

SwiftThrottle - A thread safe throttle written in Swift licensed under MIT. Introduction This throttle is intended to prevent the program from crashing

Lakr Aream 6 Jan 3, 2023
Are you sure the chemical compounds of your daily use are 100% safe? Use Chem-Aware, identify them right now!

View Project On Devpost: Built With: PubChem's REST API How To Install Chem Aware: Prerequiste: Latest Version of Xcode and Simulators installed The a

Jerry Zhang 5 Aug 23, 2022
SwiftTypeReader - You can gather type definitions from Swift source code.

SwiftTypeReader - You can gather type definitions from Swift source code.

omochimetaru 23 Dec 12, 2022
Type-based input validation.

Ensure Type-based input validation try Ensure<PackageIsCool>(wrappedValue: packages.ensure) Validators A Validator is a type that validates an input.

Build Passed 5 Jan 22, 2022
React Native utility library around image and video files for getting metadata like MIME type, timestamp, duration, and dimensions. Works on iOS and Android using Java and Obj-C, instead of Node 🚀.

Qeepsake React Native File Utils Extracts information from image and video files including MIME type, duration (video), dimensions, and timestamp. The

Qeepsake 12 Oct 19, 2022