How do I access program arguments in Swift? How do I access program arguments in Swift? swift swift

How do I access program arguments in Swift?


Process was just renamed into CommandLine (since Swift 3.0 August 4 snapshot)

let arguments = CommandLine.arguments

(for some reason this wasn't mentioned on the changelog)


Process.arguments is your friend!

Fortunately this is much easier, and built in: no importing anything, no getting your hands dirty with C, objective or otherwise.

Consider this, let's call it args.swift:

Swift 2 version:

var c = 0;for arg in Process.arguments {    println("argument \(c) is: \(arg)")    c++}

Swift 3 version:

var c = 0;for arg in CommandLine.arguments {    print("argument \(c) is: \(arg)")    c += 1}

We can compile and run it like this:

$ swift -o args args.swift && ./args fee fi fo fumargument 0 is: ./argsargument 1 is: feeargument 2 is: fiargument 3 is: foargument 4 is: fum

Note that the first argument is the program name, as you might expect.

It seems every argument is a String, as you might also expect.

I hope very much that Process becomes more useful as Swift matures, but right now it seems to only give you the arguments. Which is a lot, if you're trying to write a pure-Swift program.


As soon as your app is up I'd use the process info:

let args = NSProcessInfo.processInfo().argumentsprint(args)

Nothing unsafe there, very convenient.

Note that you have to import Foundation (or Cocoa / UIKit).