Swift
command line arguments
Swift programming
command line interface
Swift tutorial

How do you access command line arguments in Swift?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

In a Swift command-line program, arguments are available as an array of strings. The most common entry point is CommandLine.arguments, where the first element is the executable path and the remaining elements are the arguments supplied by the user.

Read Raw Arguments with CommandLine.arguments

For simple tools, this is all you need:

swift
1import Foundation
2
3let args = CommandLine.arguments
4print(args)

If you run a program like this:

bash
swift run MyTool hello world

then the argument array conceptually contains:

  • the executable path or command name
  • 'hello'
  • 'world'

That means the first user argument is usually at index 1, not index 0.

Access Specific Arguments Safely

If your tool expects required input, check the array length before indexing into it. That avoids out-of-range crashes and gives you a chance to print usage text.

swift
1import Foundation
2
3guard CommandLine.arguments.count > 1 else {
4    print("Usage: mytool <name>")
5    exit(1)
6}
7
8let name = CommandLine.arguments[1]
9print("Hello, \(name)")

This is the normal pattern for small Swift utilities. It keeps the parsing rules obvious and makes failure conditions explicit.

ProcessInfo.processInfo.arguments Is an Alternative

Swift also exposes the same concept through Foundation:

swift
1import Foundation
2
3let args = ProcessInfo.processInfo.arguments
4print(args)

For everyday CLI work, this is similar to CommandLine.arguments. Most developers choose CommandLine.arguments because it is shorter and clearly tied to command-line behavior, but either form is valid.

Parse Simple Flags Manually

For a tiny script or tool, you can often parse one or two flags by hand:

swift
1import Foundation
2
3let args = CommandLine.arguments.dropFirst()
4var verbose = false
5var name: String?
6
7for arg in args {
8    if arg == "--verbose" {
9        verbose = true
10    } else {
11        name = arg
12    }
13}
14
15if verbose {
16    print("Verbose mode enabled")
17}
18
19if let name {
20    print("Hello, \(name)")
21} else {
22    print("No name provided")
23}

This works well for small tools, but once the program has many options, subcommands, or validation rules, manual parsing becomes harder to maintain.

Understand What Swift Receives from the Shell

Swift does not parse quoting or option syntax for you. By the time the process starts, the shell has already split the command line into strings. Swift simply exposes that resulting list.

That is why shell quoting still matters. If the shell passes one argument containing spaces, Swift sees one string. If the shell splits it into several arguments, Swift sees several strings. Many command-line bugs are really shell-usage bugs rather than Swift parsing bugs.

For real CLI applications, a parser library such as Swift Argument Parser is usually the better long-term choice. It provides typed options, help text, validation, and a cleaner program structure. Still, understanding CommandLine.arguments is important because every higher-level parser ultimately starts from the same raw argument list.

Common Pitfalls

The most common mistake is forgetting that arguments[0] is the executable path rather than the first user-supplied argument.

Another issue is indexing into the array without checking the count first. That leads to avoidable runtime crashes.

People also sometimes build a large command-line interface with ad hoc loops and string comparisons when a dedicated parser library would make the program clearer and safer.

Summary

  • Use CommandLine.arguments for the simplest and most direct access to Swift CLI arguments.
  • The first element is the executable path, so user arguments start after that.
  • Check count before indexing to avoid out-of-range failures.
  • 'ProcessInfo.processInfo.arguments is a similar alternative.'
  • For complex CLIs, move from manual parsing to a dedicated argument parser library.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.