Ad space (banner)
๐ŸฆSwift Lessons
Lesson 55 / 68

Reading Command-Line Arguments

In this lesson you will learn how to read command-line arguments with CommandLine.arguments in Swift, so values can be passed in from outside when the program runs. This is for anyone searching for "Swift CommandLine.arguments how to use".

The CommandLine.arguments array holds the command-line arguments (the first element is the path of the executable itself). It is essential whenever you want a command-line tool whose options can be switched at run time.

The sample code checks whether an argument was supplied with args.count > 1, and uses a ternary operator to take args[1] as the name when there is one and fall back to "Anonymous" when there is not.

A common stumbling block for beginners is forgetting the case where no argument was supplied. Reaching straight for args[1] errors out when nothing was passed, so check args.count first.

In real-world development this also serves as the foundation of simple automation scripts that branch on the values supplied at run time.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Swift directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)