Snippet: @EnvironmentVariable
If you are creating commandline apps you sometimes need to acces the operating system environment variables, while you can use getenv(name)
it can come in handy to use a property wrapper if you need to access the environment variables often, or if you are updating them.
Full code:
/// A property wrapper to set and get system's environment variables values.
///
/// ```
/// @EnvironmentVariable(name: "PATH")
/// var path: String?
/// ```
@propertyWrapper
public struct EnvironmentVariable {
var name: String
public var wrappedValue: String? {
get {
guard let pointer = getenv(name) else { return nil }
return String(cString: pointer)
}
set {
guard let value = newValue else {
unsetenv(name)
return
}
setenv(name, value, 1)
}
}
}
in the future i'll post more about @propertyWrappers.
Read more
- Hacktoberfest 2024 • 4 minutes reading time.
- Building an Asynchronous Button in SwiftUI • 6 minutes reading time.
- @Environment variables • 4 minutes reading time.
Share
Share Mastodon Twitter LinkedIn Facebook