CommandLine
Swift can be used to develop command-line programs, and it can handle command-line arguments. With this language we can access arguments from the CommandLine
type.
The first string
in the CommandLine
arguments array is the file name of the program being run. We can remove this with range syntax.
To use this program, we need to run it from the command line. It is possible to save it in a text file, and then from the command line, run the "swift" command on it.
CommandLine
type. We can use the expression directly or store it in a local variable.string
value.for
-loop that uses switch
on each argument (past the first). We can handle arguments in a real program this way.// Step 1: get command line arguments. let args = CommandLine.arguments // Step 2: print count of arguments. print("COUNT:", args.count) // Step 3: print command line arguments. for arg in args { print("ARG:", arg) } // Step 4: skip over program file name. for arg in args[1...] { print("SKIPPED ARG:", arg) } // Step 5: switch on arguments. for arg in args[1...] { switch arg { case "argument1": print("FIRST ARG") case "argument2": print("SECOND ARG") default: print("?") } }swift program.swift argument1 argument2 COUNT: 3 ARG: program.swift ARG: argument1 ARG: argument2 SKIPPED ARG: argument1 SKIPPED ARG: argument2 FIRST ARG SECOND ARG
Swift provides the CommandLine.arguments
array which can be accessed in command-line programs. This feature simplifies how we access arguments to the current program being run.