This post covers more common tasks when writing Swift scripts, following the post on an introduction to Swift scripting.


You can invoke shell to execute:

func shell(launchPath: String, arguments: [String]) -> String {
    let task = NSTask()
    task.launchPath = launchPath
    task.arguments = arguments
    let pipe = NSPipe()
    task.standardOutput = pipe
    let data = pipe.fileHandleForReading.readDataToEndOfFile()
    let output: String = NSString(data: data, encoding: NSUTF8StringEncoding)! as String
    return output

To use:

shell("/bin/pwd", arguments: [])
shell("/bin/cp", arguments: ["/path/to/file", "/path/to/another/file"])

Launch Arguments

Pass in launch arguments to your script with NSProcessInfo.

let arguments = NSProcessInfo.processInfo().arguments as [String]
let dashedArguments = arguments.filter({$0.hasPrefix("-")})

for argument : NSString in dashedArguments {
    let key = argument.substringFromIndex(1)
    let value : AnyObject? = NSUserDefaults.standardUserDefaults().valueForKey(key)

Note that the value is retrievable via NSUserDefaults

Example: ./main.swift -s 123 --mode godlike --nokill

Keys: s, -mode and -nokill Values: 123 (integer), godlike (string) and nil




Back to Home