zneak zneak - 4 years ago 171
Swift Question

How do I access program arguments in Swift?

C and derivatives have

) parameters to their entry point functions, but Swift doesn't have one proper: top-level code is just code and it doesn't have parameters.

How can one access the equivalent of
in a Swift program?

Answer Source

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:

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

We can compile and run it like this:

$ swift -o args args.swift && ./args fee fi fo fum
argument 0 is: ./args
argument 1 is: fee
argument 2 is: fi
argument 3 is: fo
argument 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download