Instantly share code, notes, and snippets.

Embed
What would you like to do?
Using Swift 4.2's @dynamicMemberLookup to expose environment variables
import Darwin
@dynamicMemberLookup
struct Environment {
subscript(dynamicMember name: String) -> String? {
get {
guard let value = getenv(name) else { return nil }
return String(validatingUTF8: value)
}
nonmutating set {
if let value = newValue {
setenv(name, value, /*overwrite:*/ 1)
} else {
unsetenv(name)
}
}
}
}
let environment = Environment()
print("Username = \(environment.USER ?? "<unknown user>")")
print("Changing username...")
environment.USER = "admin"
print("Username = \(environment.USER ?? "<unknown user>")")
print("Deleting username...")
environment.USER = nil
print("Username = \(environment.USER ?? "<unknown user>")")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment