Swift: Command line boilerplate

import Foundation

let argv = NSProcessInfo.processInfo().arguments
let appname = (argv[0] as String).bridgeToObjectiveC().lastPathComponent
let argc = argv.count

func usage() {
    println("Usage: \(appname) arguments")
    Foundation.exit(-1)
}

if (argc < 2) {usage()}

3 Comments

  • You should look at the built-in Process.arguments. Bypasses the need for Foundation.

  • import Darwin

    let appname = Process.arguments[0].lastPathComponent
    let argc = Process.arguments.count

    func usage() {
    println(“Usage: (appname) arguments”)
    exit(-1) // Darwin.exit(-1) works too
    }
    if (argc < 2) {usage()}
    exit(0)

  • Hello Erica, I’m rather new to Swift and I’m a bit stumped so I was hoping you could provide a clue since I’m not finding a lot of information other than what you have here and nothing works. I need to grab an argument from the console, which is a directory path. When I return the value, argv[1], and try and use it as a string for a file enumeration it throws a “nil while unwrapping an Optional value”. It prints fine and I get the full path as expected, but it’s unusable as a string. If I use .lastPathComponent it only gives me the last folder of the path. Any ideas?

    Thanks in advance for any guidance you can provide.