How do you access command line arguments in Swift?
Update 01/17/17: Updated the example for Swift 3. Process
has been renamed to CommandLine
.
Update 09/30/2015: Updated the example to work in Swift 2.
It's actually possible to do this without Foundation or C_ARGV
and C_ARGC
.
The Swift standard library contains a struct CommandLine
which has a collection of String
s called arguments
. So you could switch on arguments like this:
for argument in CommandLine.arguments { switch argument { case "arg1": print("first argument") case "arg2": print("second argument") default: print("an argument") }}
Use the top level constants C_ARGC
and C_ARGV
.
for i in 1..C_ARGC { let index = Int(i); let arg = String.fromCString(C_ARGV[index]) switch arg { case "this": println("this yo"); case "that": println("that yo") default: println("dunno bro") }}
Note that I'm using the range of 1..C_ARGC
because the first element of the C_ARGV
"array" is the application's path.
The C_ARGV
variable is not actually an array but is sub-scriptable like an array.