Created
May 2, 2018 16:59
-
-
Save DougGregor/68259dd47d9711b27cbbfde3e89604e8 to your computer and use it in GitHub Desktop.
Using Swift 4.2's @dynamicMemberLookup to expose environment variables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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