Created
May 2, 2024 12:48
-
-
Save macshome/f33f252f5c48d415830d720a7261d249 to your computer and use it in GitHub Desktop.
A playground to see different ways to get environment variables in Swift
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 Foundation | |
// A playground to see different ways to get environment variables in Swift | |
// Foundation is the easiest way using the awesome ProcessInfo class. | |
// Get all of the environment variables for your running process in a Dictionary. | |
let foundationEnv = ProcessInfo().environment | |
print("********** ProcessInfo Environment **********") | |
foundationEnv.forEach { print($0) } | |
// You can use subscript to just get the one you want. | |
if let foundationUser = foundationEnv["USER"] { | |
print("\n********** ProcessInfo Singe Value **********") | |
print(foundationUser) | |
} | |
// You can also drop down to Darwin and use the standard POSIX tools. | |
// Note that these are just for the POSIX environment and won't have | |
// all of the Foundation runtime specific values. | |
// Get all of the environment variables for your process like you are on a VAX. | |
let posixEnv = environ | |
// There are a lot of ways to slice and dice an array of CCHar values. | |
// This way is a lazy one to convert it to [UnsafeMutablePointer<CChar>?]. | |
let bufray = Array(UnsafeBufferPointer(start: posixEnv, count: MemoryLayout.stride(ofValue: posixEnv))) | |
print("\n********** POSIX Environment **********") | |
// Old fashioned fast enumeration still works fine in Swift. | |
// I added an internal if-let so that there is no forced unwrapping. | |
for item in bufray { | |
if let item { | |
print(String(cString: item)) | |
} | |
} | |
// Get just the variable you want like it's 1979. | |
let posixUser = String(cString: getenv("USER")) | |
print("\n********** POSIX Single Value **********") | |
print(posixUser) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example output: