How do you access command line arguments in Swift?

Anthony Mittaz picture Anthony Mittaz · Jun 4, 2014 · Viewed 41k times · Source

How do you access command line arguments for a command line application in Swift?

Answer

Mark Adams picture Mark Adams · Jul 12, 2014

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 Strings 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")
    }
}