The first step is to add this to the top of your Swift script:
#!/usr/bin/swiftThe second step is to make it executable
$ chmod +x script.swiftFor simple scripts, Xcode Playgrounds are a great IDE. Your code runs the same way it would in the command line, you get autocomplete, live previews and a console output.
For more complex scripts, it is possible to hack Atom into a Swift scripting IDE with the following package installs:
$ apm install script language-swiftThird party libraries need to be compiled as dynamic frameworks - this can be achieved manually or with Carthage or Cocoapods (via the Rome plugin).
To include in your script, you need to specify a target and a framework path in your shebang
#!/usr/bin/swift -target x86_64-macosx10.12 -F /Library/Frameworks -F RomeYou can access launch arguments using:
CommandLine.argumentsYou can ask for user input using:
letstring=readLine()You can run shell commands using Process() (formerly NSTask) using this function (make sure to import Foundation).
func shell(_ command:String){letarguments= command.components(separatedBy:"")letprocess=Process()
process.launchPath ="/usr/bin/env"
process.arguments = arguments
process.waitUntilExit()
process.launch()}There's no NSBundle when writing a Swift script. To get the current path use
letcurrentPath=FileManager.default.currentDirectoryPathYou can't return in a Swift script. To end the context, use:
exit(1)You can format a line by adding color using the following struct:
structcommandLineFormat{staticletblack="\u{001B}[0;30m"staticletred="\u{001B}[0;31m"staticletgreen="\u{001B}[0;32m"staticletyellow="\u{001B}[0;33m"staticletblue="\u{001B}[0;34m"staticletmagenta="\u{001B}[0;35m"staticletcyan="\u{001B}[0;36m"staticletwhite="\u{001B}[0;37m"}The function breaks down a command into a string array of arguments by separating on " ". This is somewhat hacky as there are actual spaces you might want to keep.
Additionally, you may wish to capture the output from the process.
Here is an advanced example:
letshellSeparator="␣"func shell(_ command:String)->String{vararguments= command.components(separatedBy:"")
arguments = arguments.map{ $0.replacingOccurrences(of: shellSeparator, with:"")}letpipe=Pipe()letprocess=Process()
process.launchPath ="/usr/bin/env"
process.arguments = arguments
process.standardOutput = pipe
process.waitUntilExit()
process.launch()letdata= pipe.fileHandleForReading.readDataToEndOfFile()returnString(data: data, encoding:String.Encoding.utf8)}