Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save DougGregor/68259dd47d9711b27cbbfde3e89604e8 to your computer and use it in GitHub Desktop.
Save DougGregor/68259dd47d9711b27cbbfde3e89604e8 to your computer and use it in GitHub Desktop.
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