CommandLine arguments Use
This page was last reviewed on Nov 24, 2023.
Dot Net Perls
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.
Some details. The first string in the CommandLine arguments array is the file name of the program being run. We can remove this with range syntax.
Example. 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.
Step 1 We access the arguments array from the CommandLine type. We can use the expression directly or store it in a local variable.
Step 2 Like any array in Swift, we can access the element with the count property. This includes the initial element (the file name).
Step 3 We can loop over the entire array and print each value, which is a string value.
Step 4 With range syntax, we can remove the initial file name argument from the array. This can simplify some loops.
Step 5 Here is a 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
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 24, 2023 (new).
© 2007-2024 Sam Allen.