Command Line Arguments
This page is under construction. Please come back later.
When running programs from the command line we have the option of supplying additional information in the form of arguments on the command line. Command line arguments take the form of strings separated by spaces. For example the following command line program invokation has three additional arguments.
$ swift Program.swift Fred 123 Flintstone
In our programs we can access each of these arguments using the variables
Process.arguments[0]
, Process.arguments[1]
, Process.arguments[2]
, etc.
The program name can be found in the variable with the 0 subscript. The user supplied arguments are in the variables with subscripts 1, 2, 3, etc.
#!/usr/bin/env swift; import Foundation import Utils // Begin Main print("Number of arguments: " + String((CommandLine.arguments.count - 1))) print("Program Name: " + CommandLine.arguments[0]) print("Arg 1: " + CommandLine.arguments[1]) print("Arg 2: " + CommandLine.arguments[2]) print("Arg 3: " + CommandLine.arguments[3]) print("Arg 4: " + CommandLine.arguments[4]) exit(EXIT_SUCCESS)
Output
If we want to treat a command line argument as a number we first need to convert from the string representation passed on the command line to a numeric type. This is where conversion functions come in handy. The example below illustrates how to convert command line arguments to integers.
#!/usr/bin/env swift; import Foundation import Utils // Begin Main let a:Int = Int(CommandLine.arguments[1]) ?? 0 let b:Int = Int(CommandLine.arguments[2]) ?? 0 let c:Int = a + b print(Utils.format("{0:d} + {1:d} = {2:d}", a, b, c)) exit(EXIT_SUCCESS)
Output
The example below converts the command line arguments to floating point values.
#!/usr/bin/env swift; import Foundation import Utils // Begin Main let a:Double = Double(CommandLine.arguments[1]) ?? 0 let b:Double = Double(CommandLine.arguments[2]) ?? 0 let c:Double = a + b print(Utils.format("{0:f} + {1:f} = {2:f}", a, b, c)) exit(EXIT_SUCCESS)
Output
Questions
- {{Who's on first?}}
- {{Who's on second?}}
- {{Who's on third?}}
Projects
More ★'s indicate higher difficulty level.
- Combined FICA Tax (Command Line Argument)
- Cubic Roots (Command Line)
- Dog Years (Command Line)
- Milky Way Stellar Density Estimate
- Quadratic Roots (Command Line)
References
- [[Swift Community]]
- [[Swift Language Guide]]
- [[Swift Language Reference]]
- [[Swift Programming Language]], Apple Inc.
- [[Swift Doc]]
- [[We Heart Swift]]
- [[Swift Cookbook]]
- [[Swift Playground]]
- [[Swift at TutorialsPoint]]
- [[Hacking with Swift]]