Home
Swift
CommandLine arguments Use
Updated 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.
Array
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.
for
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.
switch
// 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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Nov 24, 2023 (new).
Home
Changes
© 2007-2025 Sam Allen