Creating command-line tool in Swift
This question comes up often on Swift mailing lists. Once you learn Swift, you’ll get addicted and want to use it everywhere. It’s not quite as straightforward writing a script in Swift as it is in python or bash. However, there are lots of benefits.
It’s a great entry point into learning Swift for those that typically write scripts rather than applications
You want to execute a bunch of shell commands, but you can use Swift’s rich data structures, straightforward programming language, and the huge Cocoa API.
Here’s what you can do:
Launch Xcode
File > New > ProjectChoose macOS
Click on Command Line Tool
Name it and save the project
Click on main.swift in the sidebar
Replace the Hello, World line with this code.
import Foundation
struct Shell {
func stripWhitespace(_ inString: String) -> String {
return inString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
func executeCommand(_ command:String, echo: Bool = true) -> String {
let process = Proce…
Keep reading with a 7-day free trial
Subscribe to Tech Reflect to keep reading this post and get 7 days of free access to the full post archives.